如何在字体上绘制轮廓(Pygame)

时间:2019-01-25 10:08:13

标签: python fonts pygame outline

我可以在字体上绘制轮廓吗?我想使用黑色字体,但是背景必须是黑色的,因此很难看到字体。我假设myfont.render不支持字体上的绘图轮廓。还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

Pygame不支持开箱即用,但是一种实现方法是将文本呈现为轮廓颜色,然后将其blit到移位的结果表面多次,然后以所需颜色呈现在屏幕顶部它。

pgzero使用此技术;其代码的精简版本如下所示:

import pygame

_circle_cache = {}
def _circlepoints(r):
    r = int(round(r))
    if r in _circle_cache:
        return _circle_cache[r]
    x, y, e = r, 0, 1 - r
    _circle_cache[r] = points = []
    while x >= y:
        points.append((x, y))
        y += 1
        if e < 0:
            e += 2 * y - 1
        else:
            x -= 1
            e += 2 * (y - x) - 1
    points += [(y, x) for x, y in points if x > y]
    points += [(-x, y) for x, y in points if x]
    points += [(x, -y) for x, y in points if y]
    points.sort()
    return points

def render(text, font, gfcolor=pygame.Color('dodgerblue'), ocolor=(255, 255, 255), opx=2):
    textsurface = font.render(text, True, gfcolor).convert_alpha()
    w = textsurface.get_width() + 2 * opx
    h = font.get_height()

    osurf = pygame.Surface((w, h + 2 * opx)).convert_alpha()
    osurf.fill((0, 0, 0, 0))

    surf = osurf.copy()

    osurf.blit(font.render(text, True, ocolor).convert_alpha(), (0, 0))

    for dx, dy in _circlepoints(opx):
        surf.blit(osurf, (dx + opx, dy + opx))

    surf.blit(textsurface, (opx, opx))
    return surf

def main():
    pygame.init()

    font = pygame.font.SysFont(None, 64)

    screen = pygame.display.set_mode((350, 100))
    clock = pygame.time.Clock()

    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        screen.fill((30, 30, 30))

        screen.blit(render('Hello World', font), (20, 20))

        pygame.display.update()
        clock.tick(60)

if __name__ == '__main__':
    main()

enter image description here

答案 1 :(得分:2)

如果您是初学者并且不寻找非常复杂的代码,并且您只使用简单的字体,例如 arial、helvetica、calibri 等... 您可以在“角落”中将轮廓颜色的文本 blit 4 次,然后将实际文本 blit 覆盖它:

white = pygame.Color(255,255,255)
black = pygame.Color(0,0,0)

def draw_text(x, y, string, col, size, window):
    font = pygame.font.SysFont("Impact", size )
    text = font.render(string, True, col)
    textbox = text.get_rect()
    textbox.center = (x, y)
    window.blit(text, textbox)

x = 300
y = 300

# TEXT OUTLINE

# top left
draw_text(x + 2, y-2 , "Hello", black, 40, win)
# top right
draw_text(x +2, y-2 , "Hello", black, 40, win)
# btm left
draw_text(x -2, y +2 , "Hello", black, 40, win)
# btm right
draw_text(x-2, y +2 , "Hello", black, 40, win) 

# TEXT FILL

draw_text(x, y, "Hello", white, 40, win)