Skip to content

Commit 127a687

Browse files
committed
improve shapefile.GlyphCache setup
If space and "A" glyphs are not present: - use cap-height as default space-width - create empty box representation (tofu) based on cap-height and default space-width
1 parent 5ea1c24 commit 127a687

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

src/ezdxf/fonts/shapefile.py

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -924,7 +924,7 @@ def __init__(self, font: ShapeFile) -> None:
924924
self.font: ShapeFile = font
925925
self._glyph_cache: dict[int, GlyphPath] = dict()
926926
self._advance_width_cache: dict[int, float] = dict()
927-
self.space_width: float = self.detect_space_width()
927+
self.space_width: float = self.detect_space_width(default_width=font.cap_height)
928928
self.empty_box: GlyphPath = self.get_empty_box()
929929
self.font_measurements: FontMeasurements = self._get_font_measurements()
930930

@@ -934,24 +934,43 @@ def get_scaling_factor(self, cap_height: float) -> float:
934934
except ZeroDivisionError:
935935
return 1.0
936936

937-
def detect_space_width(self) -> float:
938-
if 32 not in self.font.shapes:
937+
def detect_space_width(self, default_width: float) -> float:
938+
# space (32) or "A" (65) may not present!
939+
if 32 in self.font.shapes:
940+
return self.get_shape(32).end.x # width of space
941+
if 65 in self.font.shapes:
939942
return self.get_shape(65).end.x # width of "A"
940-
space = self.get_shape(32)
941-
return space.end.x
942-
943-
def get_empty_box(self) -> GlyphPath:
944-
glyph_A = self.get_shape(65)
945-
box = BoundingBox2d(glyph_A.control_vertices())
946-
height = box.size.y
947-
width = box.size.x
948-
start = glyph_A.start
943+
return default_width
944+
945+
def get_empty_box(self, char: int = 65) -> GlyphPath:
946+
"""Returns the empty box (tofu) representation based on the size of the given
947+
character index.
948+
949+
The given index may not exist and a default box based on cap-height and space
950+
width will be created.
951+
"""
952+
# default box parameters
953+
font = self.font
954+
height = font.cap_height
955+
width = self.space_width
956+
start = Vec2(0, 0)
957+
end = Vec2(width, 0)
958+
959+
if char in font.shapes:
960+
# box parameters based on the glyph size
961+
glyph = self.get_shape(char)
962+
box = BoundingBox2d(glyph.control_vertices())
963+
height = box.size.y
964+
width = box.size.x
965+
start = glyph.start
966+
end = glyph.end
967+
949968
p = path.Path(start)
950969
p.line_to(start + Vec2(width, 0))
951970
p.line_to(start + Vec2(width, height))
952971
p.line_to(start + Vec2(0, height))
953972
p.close()
954-
p.move_to(glyph_A.end)
973+
p.move_to(end)
955974
return GlyphPath(p)
956975

957976
def _render_shape(self, shape_number) -> GlyphPath:

0 commit comments

Comments
 (0)