1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > opengl绘制位图字体c语言源代码 SFML中的位图字体(OpenGL)

opengl绘制位图字体c语言源代码 SFML中的位图字体(OpenGL)

时间:2018-12-15 14:25:21

相关推荐

opengl绘制位图字体c语言源代码 SFML中的位图字体(OpenGL)

我正在用pySFML编写一个简单的位图字体渲染器,我想问是否有更好更快的方法来解决这个问题。在

我使用VertexArray并为字符串中的每个字符创建一个四元组。每个四边形都应用了适当的纹理坐标。在

示例字体(PNG文件):

字体呈现代码:import sfml

class BitmapFont(object):

'''

Loads a bitmap font.

`chars` is string with all characters available in the font file, example: '+0123456789x'.

`widths` is mapping between characters and character width in pixels.

'''

def __init__(self, path, chars, widths, colors=1, kerning=0):

self.texture = sfml.Texture.from_file(path)

self.colors = colors

self.height = self.texture.height / self.colors

self.chars = chars

self.kerning = kerning

self.widths = widths

self.glyphs = []

y = 0

for color in range(self.colors):

x = 0

self.glyphs.append({})

for char in self.chars:

glyph_pos = x, y

glyph_size = self.widths[char], self.height

glyph = sfml.Rectangle(glyph_pos, glyph_size)

self.glyphs[color][char] = glyph

x += glyph.width

y += self.height

class BitmapText(sfml.TransformableDrawable):

'''Used to render text with `BitmapFonts`.'''

def __init__(self, string='', font=None, color=0, align='left', position=(0, 0)):

super().__init__()

self.vertices = sfml.VertexArray(sfml.PrimitiveType.QUADS, 4)

self.font = font

self.color = color

self._string = ''

self.string = string

self.position = position

@property

def string(self):

return self._string

@string.setter

def string(self, value):

'''Calculates new vertices each time string has changed.'''

# This function is slowest and probably can be optimized.

if value == self._string:

return

if len(value) != len(self._string):

self.vertices.resize(4 * len(value))

self._string = value

x = 0

y = 0

vertices = self.vertices

glyphs = self.font.glyphs[self.color]

for i, char in enumerate(self._string):

glyph = glyphs[char]

p = i * 4

vertices[p + 0].position = x, y

vertices[p + 1].position = x + glyph.width, y

vertices[p + 2].position = x + glyph.width, y + glyph.height

vertices[p + 3].position = x, y + glyph.height

vertices[p + 0].tex_coords = glyph.left, glyph.top

vertices[p + 1].tex_coords = glyph.right, glyph.top

vertices[p + 2].tex_coords = glyph.right, glyph.bottom

vertices[p + 3].tex_coords = glyph.left, glyph.bottom

x += glyph.width + self.font.kerning

def draw(self, target, states):

'''Draws whole string using texture from a font.'''

states.texture = self.font.texture

states.transform = self.transform

target.draw(self.vertices, states)

带FPS计数器的简单基准测试:

^{pr2}$

我使用的是python3.3、pysfml1.3、sfml2.0和Windows。在

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。