我正在尝试弄清楚如何在锁定unsigned char
的{{1}}成员的pixels
像素阵列上绘制彩色矩形。
以下功能应该是前者:
SDL_Surface
它可以工作,但是在通过使用void draw_rectangle(SDL_Surface* surface, int x, int y, int width, int height)
{
SDL_LockSurface(surface);
//Make each pixel black
std::vector<uint8_t> pixels(surface->h * surface->pitch, 0);
for (int dy = y; dy < height; dy++) {
for (int dx = x; dx < width; dx++) {
pixels[dx + dy] = 0;
pixels[dx + dy + 1] = 255;
pixels[dx + dy + 2] = 0;
}
}
memcpy(surface->pixels, pixels.data(), surface->pitch * surface->h);
SDL_UnlockSurface(surface);
}
将修改后的曲面转换为纹理并将纹理复制到屏幕来测试它时,它只显示一个绿色像素:
答案 0 :(得分:1)
我已经意识到我的指针运算是错误的,我需要考虑垂直偏移,因为我将2D值映射到单维值。它有助于在纸上起草想法。
以下是代码:
void draw_rectangle(SDL_Surface* surface, int x, int y, int width, int height)
{
SDL_LockSurface(surface);
std::vector<uint8_t> pixels(surface->h * surface->pitch, 0);
int dy, dx;
int maxwidth = width * 3;
for (dy = y; dy < height; dy++) {
for (dx = x; dx < maxwidth; dx += 3) {
pixels[dx + (dy * surface->pitch)] = 0;
pixels[dx + (dy * surface->pitch) + 1] = 255;
pixels[dx + (dy * surface->pitch) + 2] = 0;
}
}
memcpy(surface->pixels, pixels.data(), surface->pitch * surface->h);
SDL_UnlockSurface(surface);
}