如何在SDL中创建颜色渐变

SDL没有这样的function,好奇,如果过去有人做过这件事,并且不介意让我朝着正确的方向前进。 我想在两种颜色之间创建一个渐变,以反映在矩形的高度上。

只需在所需的y位置上循环,您可以在其中:

  1. 通过在渐变的端点颜色之间进行插值来计算所需的颜色。
  2. 调用SDL_SetRenderDrawColor()来设置颜色。
  3. 调用SDL_RenderDrawLine()在当前y位置绘制一条水平线。

我昨天自己正在思考这个问题,我有一个有趣的想法。 如果将渲染器缩放设置为线性,则可以将几个像素的纹理缩放到所需的任何尺寸,并在颜色之间进行平滑插值 – 实质上,硬件加速纹理过滤为您提供渐变而无需CPU提升手指:计算它们。

我测试了这个,并且能够在每个角落创建一个具有不同颜色的任意矩形,并且仅使用四像素纹理在两者之间进行平滑混合。 我遇到的唯一问题是,在我的Windows机器上,纹理插值在边缘处混合为灰色并且稍微启动了颜色部分。幸运的是,将源纹理从2×2图像扩展到4×4图像并从中进行blitting中心2×2平方固定了这个,重现了我在Devuan机器上得到的结果。

当然,这本身只能给你沿X轴或Y轴的渐变或目标矩形的斜边,但这足以使用,我确信旋转特征的巧妙应用可以给你任意角度的渐变。 这是代码:

 // 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.