Fixed multiline text.

This commit is contained in:
The Wobbler 2024-03-22 20:30:49 +01:00
parent 7113e6a8c8
commit 7a2cd3e984

47
pg.py
View file

@ -254,18 +254,20 @@ class MultilineText:
Creates a surface with text on it.
You can use a "\\n" to create a newline.
When the max_width parameter is set, newlines generate automatically.
When you know the width of a single character in your font, yau can set the char_width parameter. It will make the text creation a bit faster.
When you know the width of the widest character in your font, yau can set the char_width parameter. It will make the text creation a bit faster.
Use "surface.blit(multiline_text.surface, pos)" to draw it on a surface.
"""
def __init__(self, text: str, font: pygame.font.Font=default_font, color: tuple=white, max_width: int=None, char_width: int=None):
def __init__(self, text: str, font: pygame.font.Font=default_font, color: tuple=white, max_chars: int=None, max_width: int=None, char_width: int=None):
self.text = text
self.font = font
self.color = color
self.max_width = max_width
self.char_width = char_width
self.max_chars = max_chars
if char_width is None: # get the width of a character by the font
self.char_width = font.render("A", True, white).get_width()
if char_width is None:
char_width = font.render(".", True, white).get_width() # get the width of a character by the font
if max_chars is None and not max_width is None:
self.max_width = max_width // char_width
self.surface = self.generate_surface()
@ -273,28 +275,33 @@ class MultilineText:
lines = []
line = ""
i = 0
length = 1
if not self.char_width is None:
for char in self.text:
if char == "\n" or (i + 1) * self.char_width > self.max_width:
lines.append(line)
line = ""
else:
line += char
else:
if self.max_width is None:
for char in self.text:
if char == "\n":
lines.append(line)
line = ""
line = char
length = 1
else:
line += char
if not lines:
lines = [line]
length += 1
else:
for char in self.text:
if char == "\n" or len(line) + 1 > self.max_width:
lines.append(line)
line = char
length = 1
else:
line += char
length += 1
lines.append(line)
texts = []