【问题标题】:How to add color gradient to rectangle in Pygame?如何在 Pygame 中为矩形添加颜色渐变?
【发布时间】:2020-06-12 02:29:33
【问题描述】:

信息:我正在使用 pygame 绘制一个矩形,但希望在矩形上添加一个渐变,以便看起来有阴影。

现在这是我的代码:

light_green = (0, 255, 0)
dark_green = (0, 100, 0)

pygame.draw.rect(screen, light_green, rect_dims) # Draws a rectangle without a gradient


问题:我想在浅绿色和深绿色之间创建一个线性过渡,而不是绘制一堆堆叠在一起的线(因为那很慢),所以有没有一种方法可以让我使用 pygame 做到这一点?

【问题讨论】:

  • Here's how to do it 使用 PIL 模块(如果没有别的,您可以使用它来生成图像文件并使用它),您可能能够适应 pygame.还有一个更通用的方法来描述另一个 answer of mine 中涉及的数学。
  • 您也可以定义一个小位图,然后使用smoothscale 将其拉伸到一定大小。这将创建一个渐变。
  • 你能举个例子吗?
  • @Kingsley:这是一个很好的建议!我过去曾使用过一种非常相似的技术(在 C++ 中),它具有一个能够缩放和转换图像文件的库(就像我相信 pygame 可以做到的那样)。
  • Leon: smoothscaledocumented 并且在 pygame documentation 中有使用它的示例。

标签: python pygame gradient linear-gradients rect


【解决方案1】:

这里是使用 smoothscale 的快速测试。它从一个 2x2 彩色位图开始,然后在将结果绘制到屏幕之前任意缩放它。

虽然 PyGame 将使用硬件(如果可用)来进行拉伸,但我不认为这会非常快。

import pygame

# Window size
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400

### initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Gradient Rect")

def gradientRect( window, left_colour, right_colour, target_rect ):
    """ Draw a horizontal-gradient filled rectangle covering <target_rect> """
    colour_rect = pygame.Surface( ( 2, 2 ) )                                   # tiny! 2x2 bitmap
    pygame.draw.line( colour_rect, left_colour,  ( 0,0 ), ( 0,1 ) )            # left colour line
    pygame.draw.line( colour_rect, right_colour, ( 1,0 ), ( 1,1 ) )            # right colour line
    colour_rect = pygame.transform.smoothscale( colour_rect, ( target_rect.width, target_rect.height ) )  # stretch!
    window.blit( colour_rect, target_rect )                                    # paint it


### Main Loop
clock = pygame.time.Clock()
finished = False
while not finished:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Update the window
    window.fill( ( 0,0,0 ) )
    gradientRect( window, (0, 255, 0), (0, 100, 0), pygame.Rect( 100,100, 100, 50 ) )
    gradientRect( window, (255, 255, 0), (0, 0, 255), pygame.Rect( 100,200, 128, 64 ) )
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多