justify text

This commit is contained in:
Michael Fogleman 2018-02-03 17:28:13 -05:00
parent 53d0cfa566
commit a9563efe84
2 changed files with 34 additions and 5 deletions

View File

@ -6,7 +6,7 @@ from .planner import Planner
from .turtle import Turtle from .turtle import Turtle
from .util import draw, reset from .util import draw, reset
from .hershey import text from .hershey import text, justify_text
from .hershey_fonts import ( from .hershey_fonts import (
ASTROLOGY, ASTROLOGY,
CURSIVE, CURSIVE,

View File

@ -1,17 +1,46 @@
from .hershey_fonts import * from .hershey_fonts import *
def text(string, font=FUTURAL, spacing=0): def text(string, font=FUTURAL, spacing=0, extra=0):
result = [] result = []
x = 0 x = 0
for ch in string: for ch in string:
i = ord(ch) - 32 index = ord(ch) - 32
if i < 0 or i >= 96: if index < 0 or index >= 96:
x += spacing x += spacing
continue continue
lt, rt, coords = font[i] lt, rt, coords = font[index]
for path in coords: for path in coords:
path = [(x + i - lt, j) for i, j in path] path = [(x + i - lt, j) for i, j in path]
if path: if path:
result.append(path) result.append(path)
x += rt - lt + spacing x += rt - lt + spacing
if index == 0:
x += extra
return result return result
def text_width(string, font=FUTURAL, spacing=0):
x = 0
for ch in string:
index = ord(ch) - 32
if index < 0 or index >= 96:
x += spacing
continue
lt, rt, coords = font[index]
x += rt - lt + spacing
return x
def justify_text(lines, font=FUTURAL, spacing=0):
widths = [text_width(x, font, spacing) for x in lines]
max_width = max(widths)
extras = []
for i, (line, width) in enumerate(zip(lines, widths)):
spaces = line.count(' ')
if spaces == 0:
e = 0
else:
e = float(max_width - width) / spaces
if i == len(lines) - 1:
e = 0
extras.append(e)
print width, max_width, spaces, e
return [text(line, font, spacing, extra) for line, extra in zip(lines, extras)]