How to create a color gradient in SDL

时间秒杀一切 提交于 2019-12-04 15:56:28

Just make a loop over the desired y positions, in which you:

  1. Compute the desired color by interpolating between the gradient's endpoint colors.
  2. Call SDL_SetRenderDrawColor() to set the color.
  3. Call SDL_RenderDrawLine() to draw a horizontal line at the current y position.

I was actually pondering over this myself yesterday, and I had an amusing idea. If you set the renderer scaling to linear, you can scale a texture of just a couple pixels to whatever dimensions you want and get smooth interpolation between the colors - essentially, the hardware-accelerated texture filtering gives you gradients without the CPU having to lift a finger re: calculating them.

I tested this out and was able to create an arbitrary rectangle with different colors at each corner and smooth blending in between using only a four-pixel texture. The only gotcha I ran into was that, on my Windows machine, the texture interpolation blended towards grey at the edges and started the color part a little ways in. Fortunately, expanding the source texture from a 2x2 image to a 4x4 one and blitting from the center 2x2 square fixed this, reproducing the result I got on my Devuan machine.

Of course, this by itself only gives you gradients along the X or Y axes or the hypotenuse of your destination rectangle, but that's enough to work with, and I'm sure clever application of the rotation feature could give you gradients at any arbitrary angle. Here's the code:

// Set linear blending (haven't tried this with bilinear...)
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY,"1");

// Create a 4x4 texture to serve as the source for our gradient.
uint32_t * bgpixels;
SDL_Texture * background = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA8888,
    SDL_TEXTUREACCESS_STREAMING,4,4);

// Set up the gradient colors.
// Each 2x2 quadrant of the texture has a separate color:

// AABB
// AABB
// CCDD
// CCDD
SDL_LockTexture(background,NULL,(void**)(&bgpixels),&i);
bgpixels[0] = 0x0000ffff;
bgpixels[1] = 0x0000ffff;
bgpixels[2] = 0x00ff00ff;
bgpixels[3] = 0x00ff00ff;
bgpixels[4] = 0x0000ffff;
bgpixels[5] = 0x0000ffff;
bgpixels[6] = 0x00ff00ff;
bgpixels[7] = 0x00ff00ff;
bgpixels[8] = 0xff0000ff;
bgpixels[9] = 0xff0000ff;
bgpixels[10] = 0xffffffff;
bgpixels[11] = 0xffffffff;
bgpixels[12] = 0xff0000ff;
bgpixels[13] = 0xff0000ff;
bgpixels[14] = 0xffffffff;
bgpixels[15] = 0xffffffff;
SDL_UnlockTexture(background);

// Blit it into place with the renderer.
SDL_RenderCopy(renderer,    // The SDL 2D renderer we're using
    background,             // The background texture
    &(SDL_Rect){1,1,2,2},   // We blit from the center 2x2 square to avoid a
                            // quirk on the Windows version.
    NULL);                  // The destination rectangle - just using the full
                            // target surface here.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!