| 1 |
"""This example demonstrates how to create a compatible font with Pyglets layout system using images.""" |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import pyglet |
| 5 |
from pyglet.font.user import UserDefinedMappingFont, get_scaled_user_font |
| 6 |
|
| 7 |
|
| 8 |
pyglet.resource.path.append('../../tests/data/fonts') |
| 9 |
pyglet.resource.reindex() |
| 10 |
|
| 11 |
|
| 12 |
window = pyglet.window.Window() |
| 13 |
|
| 14 |
|
| 15 |
batch = pyglet.graphics.Batch() |
| 16 |
|
| 17 |
atlas_image = pyglet.resource.image("action_man_atlas.png") |
| 18 |
|
| 19 |
|
| 20 |
atlas_characters = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.: '"/?!@#$%^&*()""" |
| 21 |
rows = 5 |
| 22 |
columns = 16 |
| 23 |
|
| 24 |
|
| 25 |
image_data = atlas_image.get_image_data() |
| 26 |
|
| 27 |
|
| 28 |
grid = pyglet.image.ImageGrid(image_data, rows=rows, columns=columns) |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
mapping = {} |
| 33 |
char = 0 |
| 34 |
for row in range(rows): |
| 35 |
for column in range(columns): |
| 36 |
y_prime = (rows - 1) - row |
| 37 |
new_index = column + y_prime * columns |
| 38 |
|
| 39 |
glyph = grid[new_index] |
| 40 |
mapping[atlas_characters[char]] = glyph |
| 41 |
char += 1 |
| 42 |
|
| 43 |
class ActionManMappedFont(UserDefinedMappingFont): |
| 44 |
glyph_fit = len(atlas_characters) |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
action_man_font = ActionManMappedFont("custom_action_man1", |
| 49 |
default_char=" ", |
| 50 |
size=13, |
| 51 |
mappings=mapping) |
| 52 |
|
| 53 |
|
| 54 |
pyglet.font.add_user_font(action_man_font) |
| 55 |
|
| 56 |
|
| 57 |
label = pyglet.text.Label("Hello World!", |
| 58 |
font_size=13, |
| 59 |
font_name="custom_action_man1", |
| 60 |
x=window.width // 2, |
| 61 |
y=window.height // 2, |
| 62 |
anchor_x="center", |
| 63 |
anchor_y="center", |
| 64 |
batch=batch) |
| 65 |
|
| 66 |
|
| 67 |
try: |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
action_scaled_32 = get_scaled_user_font(action_man_font, 32) |
| 72 |
pyglet.font.add_user_font(action_scaled_32) |
| 73 |
|
| 74 |
scaled_label = pyglet.text.Label("Scaled Hello World!", |
| 75 |
font_size=32, |
| 76 |
font_name="custom_action_man1", |
| 77 |
x=window.width // 2, |
| 78 |
y=window.height // 3, |
| 79 |
anchor_x="center", |
| 80 |
anchor_y="center", |
| 81 |
batch=batch) |
| 82 |
except ImportError: |
| 83 |
print("Warning: PIL was not detected, scaled font will not be shown.") |
| 84 |
|
| 85 |
|
| 86 |
@window.event |
| 87 |
def on_draw(): |
| 88 |
window.clear() |
| 89 |
batch.draw() |
| 90 |
|
| 91 |
|
| 92 |
pyglet.app.run() |