gpt4 book ai didi

c++ - 如何使用 SDL_CreateTexture

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:11 24 4
gpt4 key购买 nike

我想知道如何使用SDL_CreateTexture功能。
我只想创建纹理,给它一种颜色并将其绘制在屏幕上的某个位置。我不想加载任何图片。
我以为我可以按此顺序使用 SDL_CreateTexture、SDL_SetTextureColorMod、SDL_RenderCopy、SDL_RenderPresent,但我总是得到一个黑色矩形而不是红色矩形

#include <SDL.h>

int main(int argc, char* argv[]) {

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *MainWindow = SDL_CreateWindow("My Game Window",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
1024, 768,
SDL_WINDOW_SHOWN
);

SDL_Renderer *renderer = SDL_CreateRenderer(MainWindow, -1, 0);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

SDL_RenderClear(renderer);


SDL_Texture *Tile = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,8,8);

//I want my texture to be red
SDL_SetTextureColorMod(Tile,255,0,0);

//I just try this i dont know if I have to do that
SDL_SetTextureAlphaMod(Tile,255);

SDL_Rect destination = {320,240,8,8};
SDL_RenderCopy(renderer,Tile,NULL,&destination);
SDL_RenderPresent(renderer);
SDL_Delay(3000);

//Clean up
SDL_DestroyTexture(Tile);
SDL_DestroyWindow(MainWindow);
SDL_Quit();

return 0;
}


我也不知道我是否在 SDL_CreateTexture 中使用了正确的格式(SDL_PixelFormatEnum)值。他们有很多,我不明白他们的意思。 我可以使用哪一个来达到这个目的?

最佳答案

SDL_SetTextureColorMod将确保后续的渲染复制操作将考虑指定的乘数。它不会改变纹理纹素的颜色。

您应该加载位图或使用红色初始化纹理,如下例所示

int main(int argc, char* argv[]) {

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *MainWindow = SDL_CreateWindow("My Game Window",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
1024, 768,
SDL_WINDOW_SHOWN
);

SDL_Renderer *renderer = SDL_CreateRenderer(MainWindow, -1, 0);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

SDL_RenderClear(renderer);

SDL_Texture *Tile = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STREAMING, 8, 8);

// Initialize texture pixels to a red opaque RGBA value
unsigned char* bytes = nullptr;
int pitch = 0;
SDL_LockTexture(Tile, nullptr, reinterpret_cast<void**>(&bytes), &pitch);
unsigned char rgba[4] = { 255, 0, 0, 255 };
for(int y = 0; y < 8; ++y) {
for (int x = 0; x < 8; ++x) {
memcpy(&bytes[(y * 8 + x)*sizeof(rgba)], rgba, sizeof(rgba));
}
}
SDL_UnlockTexture(Tile);

SDL_Rect destination = { 320, 240, 8, 8 };
SDL_RenderCopy(renderer, Tile, NULL, &destination);
SDL_RenderPresent(renderer);
SDL_Delay(3000);

//Clean up
SDL_DestroyTexture(Tile);
SDL_DestroyWindow(MainWindow);
SDL_Quit();

return 0;
}

关于c++ - 如何使用 SDL_CreateTexture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26698378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com