如何解决如何使用pygame保存带有轮廓文本的图像?
import pygame
pygame.init()
font = pygame.font.SysFont('arialroundedbold.ttf',60)
text = font.render("hello world",True,(0,0),(255,255,255))
pygame.image.save(text,"hello_world.png")
如何在文本 "hello world" 周围添加具有特定粗体(假设为 3 分)的红色轮廓并保存?
解决方法
如果要在字母周围绘制轮廓,请参阅 Have an outline of text in Pygame。
import pygame
pygame.init()
window = pygame.display.set_mode((400,400))
def render_text_outline(font,text,color,background,outline,outlinecolor):
outlineSurf = font.render(text,True,outlinecolor)
outlineSize = outlineSurf.get_size()
textSurf = pygame.Surface((outlineSize[0] + outline*2,outlineSize[1] + 2*outline))
textSurf.fill(background)
textRect = textSurf.get_rect()
offsets = [(ox,oy)
for ox in range(-outline,2*outline,outline)
for oy in range(-outline,outline)
if ox != 0 or ox != 0]
for ox,oy in offsets:
px,py = textRect.center
textSurf.blit(outlineSurf,outlineSurf.get_rect(center = (px+ox,py+oy)))
innerText = font.render(text,color).convert_alpha()
textSurf.blit(innerText,innerText.get_rect(center = textRect.center))
return textSurf
font = pygame.font.SysFont('arialroundedbold.ttf',60)
text_outline = render_text_outline(
font,"hello world",(0,0),(255,255,255),3,0))
# save to file
pygame.image.save(text_outline,"hello_world.png")
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((127,127,127))
window.blit(text_outline,text_outline.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
如果要在文本框周围绘制轮廓,请定义轮廓的宽度和颜色:
width = 3
outline_color = "red"
创建一个 pygame.Surface
,其宽度和高度是文本的外线厚度的两倍Surface:
outline_w = text.get_width() + width*2
outline_h = text.get_height() + width*2
text_outline = pygame.Surface((outline_w,outline_h))
用轮廓的颜色填充新的Surface:
text_outline.fill(outline_color)
将文本 Surface 放在新 Surface 的中间:
text_outline.blit(text,text.get_rect(center = text_outline.get_rect().center))
最小示例:
import pygame
pygame.init()
window = pygame.display.set_mode((400,400))
font = pygame.font.SysFont('arialroundedbold.ttf',60)
text = font.render("hello world",255))
width = 3
outline_color = "red"
outline_w = text.get_width() + width*2
outline_h = text.get_height() + width*2
text_outline = pygame.Surface((outline_w,outline_h))
text_outline.fill(outline_color)
text_outline.blit(text,text.get_rect(center = text_outline.get_rect().center))
# save to file
pygame.image.save(text_outline,text_outline.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。