SDL2像素操作

SDL2像素操作

经过几天的研究,摸索出SDL2像素操作的方式

  • 操作surface中的像素
  • 操作texture中的像素

SDL2中,surface是直接放在内存中的,没有硬件加速.而surface放在显存中,有硬件加速,原理上应该效率更高.

直接贴两段代码

  • surface方式
#include <SDL2/SDL.h>

SDL_Window* window = NULL;
SDL_Surface* surface = NULL;

void init()
{
    SDL_Init(SDL_INIT_VIDEO);
    window = SDL_CreateWindow("SDL", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
    surface = SDL_GetWindowSurface(window);
}

int main()
{
    init();

    //锁定surface
    SDL_LockSurface(surface); 

    //生成一种颜色
    Uint32 color = SDL_MapRGB(surface->format, 0xff, 0, 0);

    //surface像素地址
    Uint32* pixel = (Uint32*)surface->pixels;

    //一个像素4个字节,要除以4
    for(int i = 0; i < surface->pitch / 4 * 100; i++)
        pixel[i] = color;

    SDL_UnlockSurface(surface);
    //显示
    SDL_UpdateWindowSurface(window);

    SDL_Delay(5*1000);

    SDL_FreeSurface(surface);
    SDL_Quit();
}
  • texture方式
#include <SDL2/SDL.h>

SDL_Window* gWindow = NULL;
SDL_Renderer* gRender = NULL;
SDL_Texture* gTexture = NULL;

void init()
{
    SDL_Init(SDL_INIT_VIDEO);
    gWindow = SDL_CreateWindow("SDL", 100, 100, 640, 480, SDL_WINDOW_SHOWN);

    gRender = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);

    //创建texture,注意像素格式和访问方式
    gTexture = SDL_CreateTexture(gRender, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, 640, 480);

}

void close()
{
    SDL_DestroyRenderer(gRender);
    SDL_DestroyTexture(gTexture);
    SDL_DestroyWindow(gWindow);
    SDL_Quit();
}
int main()
{
    void* pix;
    int pitch;
    SDL_PixelFormat* format;
    init();

    SDL_LockTexture(gTexture, NULL, &pix, &pitch);
    //为了生成颜色,使用rgba8888的格式
    format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
    Uint32 color = SDL_MapRGBA(format, 0xff, 0, 0, 0xff / 3);
    for(int i = 0; i < pitch * 200 / 4; i++)
        ((Uint32*)pix)[i] = color;
    SDL_UnlockTexture(gTexture);

    SDL_RenderCopy(gRender, gTexture, NULL, NULL);
    SDL_RenderPresent(gRender);

    SDL_Delay(5 * 1000);
    close();
}

SDL2也提供了将surface转化为texture的方式,本人找到的也就这么两种方式可以直接对像素进行读写.

我还发现一个窗口的surface和renderer不能都有,否则就会出现问题.并不知道这是为什么.我是在ubuntu下使用的SDL2

你可能感兴趣的:(sdl,SDL2)