Skip to content

Commit eb98202

Browse files
committed
fixed alignement of text
1 parent 7a90819 commit eb98202

File tree

1 file changed

+41
-10
lines changed

1 file changed

+41
-10
lines changed

pygame_matplotlib/backend_pygame.py

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -174,22 +174,53 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
174174
# make sure font module is initialized
175175
if not pygame.font.get_init():
176176
pygame.font.init()
177-
# prop is the fondt properties
178-
font_size = prop.get_size() * self.dpi / 57
177+
# prop is the font properties
178+
font_size = prop.get_size_in_points() * 2
179179
myfont = pygame.font.Font(prop.get_file(), int(font_size))
180180
# apply it to text on a label
181181
font_surface = myfont.render(
182182
s, gc.get_antialiased(), [val * 255 for val in gc.get_rgb()]
183183
)
184+
# Get the expected size of the font
185+
width, height = myfont.size(s)
186+
# Tuple for the position of the font
187+
font_surf_position = (
188+
x,
189+
self.surface.get_height() - y
190+
)
184191
if mtext is not None:
185-
# Reads the position of the mtext
186-
# but could use relative position to 0 instead
187-
x, y, _, _ = mtext.get_window_extent().bounds
188-
width, height = myfont.size(s)
189-
# Needs to resize to center
190-
y += height / 2
191-
x -= width / 2
192-
self.surface.blit(font_surface, (x, self.surface.get_height() - y))
192+
# Use the alignement from mtext or default
193+
h_alignment = mtext.get_horizontalalignment()
194+
v_alignment = mtext.get_verticalalignment()
195+
else:
196+
h_alignment = 'center'
197+
v_alignment = 'center'
198+
# Use the alignement to know where the font should go
199+
if h_alignment == 'left':
200+
h_offset = 0
201+
elif h_alignment == 'center':
202+
h_offset = - width / 2
203+
elif h_alignment == 'right':
204+
h_offset = - width
205+
else:
206+
h_offset = 0
207+
208+
if v_alignment == 'top':
209+
v_offset = 0
210+
elif v_alignment == 'center' or v_alignment == 'center_baseline':
211+
v_offset = - height / 2
212+
elif v_alignment == 'bottom' or v_alignment == 'baseline':
213+
v_offset = - height
214+
else:
215+
v_offset = 0
216+
# pygame.draw.circle(self.surface, (255, 0, 0), (x, self.surface.get_height() - y), 3)
217+
# pygame.draw.lines(self.surface, (0, 255, 0), True, ((x, self.surface.get_height() - y), (x + width, self.surface.get_height() - y), (x + width, self.surface.get_height() - y + height)))
218+
# Tuple for the position of the font
219+
font_surf_position = (
220+
x + h_offset,
221+
self.surface.get_height() - y + v_offset
222+
)
223+
self.surface.blit(font_surface, font_surf_position)
193224

194225
def flipy(self):
195226
# docstring inherited

0 commit comments

Comments
 (0)