能否从像素为基础的彩色图像中创建字体?(适用于Pygame,也适用于其他情况)

2024-05-15 03:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在和Pygame合作,遇到了一个问题。我想用一个金属外观的字符自定义字体,但我不知道怎么做。

更准确地说,我希望创建的文本看起来像这里的图像: gold, metallic looking text

我所知道的所有字体类型都是基于黑白(我认为是基于矢量的)图像,但据我所知,这是为了使它们具有可伸缩性并允许它们改变颜色-但是,我并不需要这种功能。

是否有一种字体格式或其他方法来创建一种“花哨”的多色字体,如上面使用的png/tif/bmp/其他一些基于像素的图片格式?


Tags: 方法图像文本功能类型png颜色矢量
3条回答

我没有找到支持颜色的位图字体格式(更不用说python3.4/pygame了),但是下面user3191557提供的另一种解决方案让我走上了正确的道路。在

最后,我创建了一个png图像,其中包含我需要的字符串(图像中所有字符的间距/大小都相等),从左到右。对我来说,我只需要0到9之间的数字。以下是我使用的代码(希望我没有遗漏任何相关内容):

import pygame

WINDOWWIDTH = 1080
WINDOWHEIGHT = 1080
Window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), pygame.FULLSCREEN)

class CustomFont: #The letterimage file must consist of equally-sized letters, each of 'lettersize', arranged in a single line, left-to-right.  The letterstring is a string representation of the letters in the image (in the same order).
    def __init__(self, letterstring, lettersize, letterimagefile):
        self.letterstring = tuple(letterstring)
        self.lettersize = lettersize
        self.letterimagefile = letterimagefile
    def write (self, string, position):
        stringseparated = tuple(string)
        for i in range(len(stringseparated)):
            letter = stringseparated[i]
            for j in range(len(self.letterstring)):
                if self.letterstring[j] == letter: #j gives us the index number of the letter in our original string
                    grabletterbox = ((self.lettersize[0] * j), 0, self.lettersize[0], self.lettersize[1]) #this defines the position of the rectangle that will grab the letter from our letterimage file, as well as the size of said rectangle     
                    Window.blit(self.letterimagefile, ((position[0] + (i * self.lettersize[0])),position[1]) , grabletterbox)

ActiveNumbersSprite = pygame.image.load('.\images\ActiveNumbers.png') #The image used for the numbers
ActiveNumbers = CustomFont('0123456789', (36 , 60), ActiveNumbersSprite) #This tells the program what characters the ActiveNumbersSprite image contains, in what order, how big each character is (as (x,y), and the name of the image file
...

有了它,我就可以用ActiveNumbers.write(string,(x,y))在窗口中的任何x,y位置用我的字体写任何我想要的字符串(当然,假设我有所需字符的图像)。很有魅力。在

我不知道PyGame,但OpenType有一些规范可以满足您的需要。唯一的问题是:呈现字体的东西必须支持这些new and bleeding edge specs。例如,在浏览器领域,这些技术中的一些在Firefox中有效,有些在IE11中,还有一些只有在Mac上作为系统字体安装时才起作用。在

但你可以做colorful game fonts like these :)

大多数“早期”字体格式都是基于位图字体的,所以你可能会很幸运。在

对于一个简单的例子,pygame here有一个“位图字体”片段。这不实现(单词)包装和其他花哨的东西。在

但是,您也可以或多或少地轻松地滚动:

  • 用你的字体创建一个大的位图,如你的例子所示。在
  • 在位图中创建一个映射字符->;矩形。在最简单的情况下,您只需要每个字符的宽度(如果所有字符的宽度相同,则更简单)
  • 在呈现函数中,以字符串作为输入和起始位置。在
  • 从字符串中查找每个字符,从左到右呈现字符,并按刚刚显示的字符宽度向左移动。在

希望有帮助

相关问题 更多 >

    热门问题