gpt4 book ai didi

python - 如何在 Pygame 中模糊曲面的边缘?

转载 作者:行者123 更新时间:2023-12-03 07:51:12 24 4
gpt4 key购买 nike

我想在 Pygame 中以“渐变方式”模糊表面的边缘。

这是我们想要的效果的示例:

  • 第一张图片没有模糊
  • 第二个正方形出现中等模糊
  • 第三个正方形上高度模糊

image of blur effects desired

Pygame 有 2 个模糊表面的函数:pygame.transform.box_blurpygame.transform.gaussian_blur。但是,它们没有像上面的示例那样在表面和屏幕之间执行渐变模糊。

最佳答案

如果您使用 pygame-ce,您可以使用新函数 pygame.transform.box_blurpygame.transform.gaussian_blur,无需拉动即可实现模糊在其他库中。

查看您提供的图像,似乎您的需求可以通过特定于区域的模糊设置来满足。

让我们使用这个示例图像:

Lord of the rings example

如果我们单独模糊特定区域,它可能看起来像这样:(在您的示例中看起来会更好,因为您的方 block 由间隙分隔)

LOTR region blur

此代码的工作原理是在所需的模糊区域中创建原始图像的子表面,模糊子表面,然后将它们传输回主表面。

import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))

img = pygame.image.load("lord_small.png").convert_alpha()

def blur_region(region, amount):
img.blit(pygame.transform.box_blur(img.subsurface(region), amount), region)

third = img.get_width() // 3
blur_region([0, 0, third, img.get_height()], 4)
blur_region([third, 0, third, img.get_height()], 8)
blur_region([third * 2, 0, img.get_width() - third * 2, img.get_height()], 12)

while True:
screen.fill("black")
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit

screen.blit(img, (0, 0))
pygame.display.flip()

但是,我们如何为模糊添加真正的渐变?我的解决方案是制作原始表面的模糊副本,然后通过创建特殊的渐变不透明度表面并使用它们来调制显示的量,逐渐从显示更多原始表面过渡到更多模糊表面。

LOTR gradient blur

import pygame

pygame.init()
screen = pygame.display.set_mode((500,500))

img = pygame.image.load("lord_small.png").convert_alpha()
img_blurred = pygame.transform.box_blur(img, 4)

alpha_surf = pygame.Surface((256, 1), pygame.SRCALPHA)
for i in range(256):
alpha_surf.set_at((i, 0), (255,255,255,i))
alpha_surf = pygame.transform.scale(alpha_surf, img.get_size())
alpha_surf_reciprocal = pygame.transform.flip(alpha_surf, True, False)

img.blit(alpha_surf_reciprocal, (0,0), special_flags=pygame.BLEND_RGBA_MULT)
img_blurred.blit(alpha_surf, (0,0), special_flags=pygame.BLEND_RGBA_MULT)

combined_img = pygame.Surface(img.get_size(), depth=32)
combined_img.blit(img, (0,0))
combined_img.blit(img_blurred, (0,0))

while True:
screen.fill("purple")

for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit

screen.blit(combined_img, (0,0))
pygame.display.flip()

关于python - 如何在 Pygame 中模糊曲面的边缘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77117250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com