SDL2入门(八)surface抠图

2025-10-22 06:04:35

1、只需修改第三节课代码便可实现(增加两个函数)。如图红色标记。

SDL2入门(八)surface抠图

2、第10行:unit32是32位无符号整型数据,SDL_MapRGB是根据参数返回一个不透明的像素值。函数参数:surface->format是surface的像素格式,后面三个参数分别是r(红red)、g(绿green)、b(蓝blue)的值。

SDL2入门(八)surface抠图

3、第11行:SDL_SetColorKey是一个抠色函数,把某个指定的像素变透明。函数参数:SDL_TRUE决定抠色,相反SDL_FALSE表示不抠色;colorkey为将要抠掉颜色的像素值。

SDL2入门(八)surface抠图

4、运行结果如图。

总结:这方法需要先知道背景色的r、g、b值才行,而且这方法对比较单一的背景颜色才好使用。

SDL2入门(八)surface抠图

5、代码:

#include <SDL2/SDL.h

#include <SDL2/SDL_image.h>

int main(int argc,char**argv)

{

SDL_Init(SDL_INIT_VIDEO);

SDL_Window*window=SDL_CreateWindow("surface抠图", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 720, 1280, SDL_WINDOW_SHOWN);

SDL_Renderer*renderer=SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

SDL_RenderClear(renderer);

SDL_Surface*surface=IMG_Load("./resource/circle.png");

Uint32 colorkey = SDL_MapRGB(surface->format, 255, 255, 255);

SDL_SetColorKey(surface, SDL_TRUE, colorkey);

SDL_Rect box={200, 400, surface->w, surface->h};

SDL_Texture*texture=SDL_CreateTextureFromSurface(renderer, surface);

SDL_RenderCopy(renderer, texture, NULL, &box);

SDL_RenderPresent(renderer);

SDL_Delay(6000);

SDL_FreeSurface(surface);

SDL_DestroyTexture(texture);

SDL_DestroyRenderer(renderer);

SDL_DestroyWindow(window);

SDL_Quit();

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢