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

本文介绍如何使用 SDL 和 SDL_image 库实现图像的背景透明化处理。通过设置 colorkey 来指定图像中需要变为透明的颜色,并展示了完整的 C++ 代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

SDL学习(四) <wbr>Color <wbr>Keying(抠色)

SDL学习(四) <wbr>Color <wbr>Keying(抠色)



#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;
}


显示结果:

demo:http://download.youkuaiyun.com/detail/sz76211822/9877623

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值