python-3.x - 在 pygame 中渲染抗锯齿透明文本

标签 python-3.x text pygame antialiasing alpha-transparency

我想要一个可以更改 alpha 值的文本,同时仍使其具有抗锯齿效果以使其看起来不错。

label1 已消除锯齿但不透明

label2 是透明的,但未抗锯齿

我想要两者兼而有之的文本。 谢谢。

import pygame
pygame.init()

screen = pygame.display.set_mode((300, 300))
font = pygame.font.SysFont("Segoe UI", 50)

label1 = font.render("hello", 1, (255,255,255))
label1.set_alpha(100)
label2 = font.render("hello", 0, (255,255,255))
label2.set_alpha(100)

surface_box = pygame.Surface((100,150))
surface_box.fill((0,150,150))

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill((150,0,150))
    screen.blit(surface_box, (40, 0))
    screen.blit(label1, (0,0))
    screen.blit(label2, (0,50))
    pygame.display.update()

pygame.quit()

如果您可以修改示例以具有这些功能,我们将不胜感激。

最佳答案

  1. 渲染文本表面。

  2. 通过传递pygame.SRCALPHA创建一个具有每像素alpha的透明表面,并用白色和所需的alpha值填充它。

  3. 将 Alpha 表面 Blit 到文本表面上,并将 pygame.BLEND_RGBA_MULT 作为 special_flags 参数传递。这将使表面的可见部分变得透明。


import pygame as pg


pg.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 64)
blue = pg.Color('dodgerblue1')
sienna = pg.Color('sienna2')

# Render the text surface.
txt_surf = font.render('transparent text', True, blue)
# Create a transparent surface.
alpha_img = pg.Surface(txt_surf.get_size(), pg.SRCALPHA)
# Fill it with white and the desired alpha value.
alpha_img.fill((255, 255, 255, 140))
# Blit the alpha surface onto the text surface and pass BLEND_RGBA_MULT.
txt_surf.blit(alpha_img, (0, 0), special_flags=pg.BLEND_RGBA_MULT)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill((30, 30, 30))
    pg.draw.rect(screen, sienna, (105, 40, 130, 200))
    screen.blit(txt_surf, (30, 60))
    pg.display.flip()
    clock.tick(30)

pg.quit()

关于python-3.x - 在 pygame 中渲染抗锯齿透明文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594895/

相关文章:

python - 为什么使用@contextmanager装饰器时需要 "try-finally"?

php - 搜索文本以找到相似之处

php 查询 mysql 文本

c++ - 在 c++ win32 中绘制/打印具有透明背景的文本

python - 使用 PyGame 显示 PyMunk - Python

python - 在Pygame中绘制五边形、六边形

python - Pygame 应用程序不会在第一次关闭

python - 文档中的单元测试示例引发 AttributeError

python - 如何使用 Python 日志库写入 CSV?

python - Python 3 的 int 可以容纳的最大值是多少?