SDL2 1 位表面,将调色板中的两种颜色之一分配给像素

问题描述 投票:0回答:1

在c ++ SDL2中,我想访问像素并在1位表面上绘制,就像我在8位表面上所做的那样,但我错过了一些我看不到的东西。

在 8 位表面中,效果很好(像素在调色板 -> 颜色中采用预期的颜色):

SDL_Surface * surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 8, SDL_PIXELFORMAT_INDEX8);
SDL_Color colors[2] = {{0, 0, 0, 255}, {255, 255, 255, 255}};
SDL_SetPaletteColors(surface->format->palette, colors, 0, 2);
Uint8* pixels = (Uint8*)surface->pixels;
    for(int i = 0; i < pixelsCount; i++){
        if(*geometrical condition*){
            pixels[i]=1;
        }else{
            pixels[i]=0;
        }
    }

对于 1 位表面,由于赋值(最后一个 if),我得到非 0 退出:

SDL_Surface * surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 1, SDL_PIXELFORMAT_INDEX1MSB);
SDL_Color colors[2] = {{0, 0, 0, 255}, {255, 255, 255, 255}};
SDL_SetPaletteColors(surface->format->palette, colors, 0, 2);
Uint8* pixels = (Uint8*)surface->pixels;
    for(int i = 0; i < pixelsCount; i++){
        if(*geometrical condition*){
            pixels[i]=1;
        }else{
            pixels[i]=0;
        }
    }

1 位情况下正确的像素分配是什么?

c++ pixel bit sdl-2 color-palette
1个回答
0
投票

嗯,这对我有用,也许这不是最好的解决方案,但是:

  1. 有效
  2. 对某人来说可以说教

提醒,每像素 1 位表面,SDL_PIXELFORMAT_INDEX1MSB。

//coordinates
int x, y;

//more pixels than in SCREEN_WIDTH, not used here, but useful for /*geom. cond.*/
int actualWidthPixels = surface1->pitch * 8;

//follow the pixel
int pixel{};

//iterate each byte
for( uint8_t* byte = pixels; byte - pixels < surface1->pitch * surface1->h; byte++)
{
    //iterate each bit in byte
    for(int bit = 0; bit < 8; bit++)
    {
        x = pixel % (surface1->pitch * 8);
        y = (byte - pixels) / surface1->pitch;//pixels = (uint8_t*)s->pixels;
    
        if (/*geometrical condition*/)
        {
            //set the bit
            *byte |= (1 << 7-bit);
        }
        pixel++;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.