-
clion新建项目,并编写代码main.cpp
#include <iostream> #include "SDL.h" #include "SDL_image.h" void drawMyRect(SDL_Renderer *sdlRenderer, SDL_Texture *sdlTexture, SDL_Rect &rect) {// SDL_Texture填充透明色(没有生效) SDL_SetRenderDrawBlendMode(sdlRenderer, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(sdlTexture, SDL_BLENDMODE_BLEND); SDL_RenderFillRect(sdlRenderer, &rect); // SDL_画红色矩形 缺点:闪烁 SDL_SetRenderDrawColor(sdlRenderer, 0xff, 0, 0, 255); rect.x++; rect.x %= rect.w; SDL_RenderDrawRect(sdlRenderer, &rect); } SDL_Rect drawBackGround(SDL_Renderer *sdlRenderer, unsigned char r, unsigned char g) {// 重新把sdl_renderer指向window SDL_SetRenderTarget(sdlRenderer, nullptr); SDL_SetRenderDrawBlendMode(sdlRenderer, SDL_BLENDMODE_NONE); SDL_SetRenderDrawColor(sdlRenderer, r, g, 255, 0); SDL_Rect srect = {0, 0, 640, 480}; return srect; } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window *sdlWindow = SDL_CreateWindow("sdl_draw_on_texture", 0, 0, 640, 480, SDL_WINDOW_ALWAYS_ON_TOP); SDL_Renderer *sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); // 创建一个SDL_Texture, 等下把图形画到texture上,再贴到window上 SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_TARGET, 400, 320); SDL_Event event; int quit = false, delayMs = 1000 / 24; SDL_Rect winRect = {0, 0, 400, 320}, texRect = {0, 0, 400, 320}; SDL_Rect rect = {100, 100, 150, 150}; while (!quit) { uint32_t startTime = SDL_GetTicks(); while (SDL_PollEvent(&event) > 0) { if (event.type == SDL_QUIT) { quit = true; } } // 设置画到SDL_Texture上 SDL_SetRenderTarget(sdlRenderer, sdlTexture); unsigned char r, g, b, a; // 先保存rgba SDL_GetRenderDrawColor(sdlRenderer, &r, &g, &b, &a); SDL_SetRenderDrawColor(sdlRenderer, 0, 0, 0, 0xff); drawMyRect(sdlRenderer, sdlTexture, rect); SDL_Rect srect = drawBackGround(sdlRenderer, r, g); // window填充蓝色 SDL_RenderFillRect(sdlRenderer, &srect); SDL_RenderCopy(sdlRenderer, sdlTexture, &winRect, &texRect); SDL_RenderPresent(sdlRenderer); uint32_t endTime = SDL_GetTicks(); if (endTime - startTime < delayMs) { SDL_Log("delay %d ", delayMs - (endTime - startTime)); SDL_Delay(delayMs - (endTime - startTime)); } } return 0; }
-
运行后就行啦
- 问题:alpha透明度没有生效
- 问题:alpha透明度没有生效