SDL2.0 扣色(png图片重叠,前景色透明)

如图,小人的背景是青色的(R:0,G:FF,B:FF),那么我们现在要将小人背景透明化,则现在的color key就是青色的。

 

SDL2.0 扣色(png图片重叠,前景色透明)_第1张图片

SDL2.0 扣色(png图片重叠,前景色透明)_第2张图片



#include "stdafx.h"
#include "include/SDL.h"
#include "SDL2_image/include/SDL_image.h"
#pragma comment(lib, "lib/x86/SDL2.lib")
#pragma comment(lib, "SDL2_image/lib/x86/SDL2_image.lib")

int _tmain(int argc, _TCHAR* argv[])
{
	SDL_Init(SDL_INIT_EVERYTHING);//SDL初始化

	SDL_Window *Screen = SDL_CreateWindow("Title", 100, 100, 640, 480, SDL_WINDOW_RESIZABLE);//创建窗口
	SDL_Renderer *render = SDL_CreateRenderer(Screen, -1, 0);//创建渲染器
	SDL_Surface *bk = IMG_Load("F:\\background.png");//SDL IMAGE扩展库读取tga图片
	SDL_Surface *foo = IMG_Load("F:\\foo.png");//SDL IMAGE扩展库读取tga图片

	//Use this function to map an RGB triple to an opaque pixel value for a given pixel format
	//format:an SDL_PixelFormat structure describing the format of the pixel
	Uint32 colorkey = SDL_MapRGB(foo->format, 0x00, 0xff, 0xff);//用画图工具提取foo.png的背景颜色,发现foo.png的背景色是0x00ffff


	//surface:the SDL_Surface structure to update
	//flag:SDL_TRUE to enable color key, SDL_FALSE to disable color key
	//key:the transparent pixel
	//Returns 0 on success or a negative error code on failure; call SDL_GetError() for more information.
	SDL_SetColorKey(foo, 1, colorkey);//Use this function to set the color key (transparent pixel) in a surface.

	SDL_Texture *texture = SDL_CreateTextureFromSurface(render, bk);//创建纹理
	SDL_Texture *texture1 = SDL_CreateTextureFromSurface(render, foo);//创建纹理

	SDL_RenderClear(render);
	SDL_RenderCopy(render, texture, NULL, NULL);//拷贝数据显示

	SDL_Rect rect;
	rect.x = 50;
	rect.y = 125;
	rect.w = foo->w;
	rect.h = foo->h;
	SDL_RenderCopy(render, texture1, NULL, &rect);//拷贝数据显示
	SDL_RenderPresent(render);

	SDL_Event event;
	while (1){
		SDL_PollEvent(&event);
		if (event.type == SDL_QUIT){
			break;
		}
	}

	SDL_FreeSurface(bk);//是否图片资源
	SDL_DestroyTexture(texture);//释放纹理
	SDL_DestroyRenderer(render);//释放渲染器
	SDL_DestroyWindow(Screen);//销毁窗口
	SDL_Quit();//退出
	return 0;
}


显示结果: SDL2.0 扣色(png图片重叠,前景色透明)_第3张图片

demo:http://download.csdn.net/detail/sz76211822/9877623

你可能感兴趣的:(SDL2.0)