Skip to content

Commit

Permalink
Double render_text() performance
Browse files Browse the repository at this point in the history
Both render_text() and text_dimensions() used to compute glyphs for
all the characters in the given text. Since text_dimensions() is
used by render_text() early on this would do the work twice almost
exactly in a row.

Speed things up by computing the glyphs early in render_text() and
also providing the precomputed data to text_dimensions().
  • Loading branch information
tanuva committed Jan 24, 2020
1 parent cb0d419 commit c5cd07b
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions PySerdisp/textrenderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,17 +180,20 @@ def kerning_offset(self, previous_char, char):
# which means that the pixel values are multiples of 64.
return int(kerning.x / 64)

def text_dimensions(self, text):
def text_dimensions(self, text, glyphs):
"""Return (width, height, baseline) of `text` rendered in the current font."""
width = 0
max_ascent = 0
max_descent = 0
previous_char = None

assert(len(text) == len(glyphs))

# For each character in the text string we get the glyph
# and update the overall dimensions of the resulting bitmap.
for char in text:
glyph = self.glyph_for_character(char)
for i in range(len(text)):
char = text[i]
glyph = glyphs[i]
max_ascent = max(max_ascent, glyph.ascent)
max_descent = max(max_descent, glyph.descent)
kerning_x = self.kerning_offset(previous_char, char)
Expand All @@ -212,15 +215,21 @@ def render_text(self, text, width=None, height=None, baseline=None):
If `width`, `height`, and `baseline` are not specified they are computed using
the `text_dimensions' method.
"""

glyphs = []
for char in text:
glyphs.append(self.glyph_for_character(char))

if None in (width, height, baseline):
width, height, baseline = self.text_dimensions(text)
width, height, baseline = self.text_dimensions(text, glyphs)

x = 0
previous_char = None
outbuffer = Bitmap(width, height)

for char in text:
glyph = self.glyph_for_character(char)
for i in range(len(text)):
char = text[i]
glyph = glyphs[i]

# Take kerning information into account before we render the
# glyph to the output bitmap.
Expand Down

0 comments on commit c5cd07b

Please sign in to comment.