Skip to content

Commit eaccde8

Browse files
committed
Add anchor_label method
1 parent 6d1d1b0 commit eaccde8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

adafruit_display_text/__init__.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Text.git"
1212

1313
from displayio import Group, Palette
14+
from micropython import const
1415

1516
try:
1617
from typing import List, Optional, Tuple
@@ -219,6 +220,17 @@ class LabelBase(Group):
219220
:param bool verbose: print debugging information in some internal functions. Default to False
220221
"""
221222

223+
# Anchor point constants for anchor_label method.
224+
ANCHOR_TOP_LEFT = const((0.0, 0.0))
225+
ANCHOR_TOP_CENTER = const((0.5, 0.0))
226+
ANCHOR_TOP_RIGHT = const((1.0, 0.0))
227+
ANCHOR_CENTER_LEFT = const((0.0, 0.5))
228+
ANCHOR_CENTER = const((0.5, 0.5))
229+
ANCHOR_CENTER_RIGHT = const((1.0, 0.5))
230+
ANCHOR_BOTTOM_LEFT = const((0.0, 1.0))
231+
ANCHOR_BOTTOM_CENTER = const((0.5, 1.0))
232+
ANCHOR_BOTTOM_RIGHT = const((1.0, 1.0))
233+
222234
def __init__(
223235
self,
224236
font: FontProtocol,
@@ -456,3 +468,33 @@ def label_direction(self, new_label_direction: str) -> None:
456468

457469
def _replace_tabs(self, text: str) -> str:
458470
return text if text.find("\t") < 0 else self._tab_text.join(text.split("\t"))
471+
472+
def anchor_label(self, anchor: Tuple[float, float], width: int, height: int) -> None:
473+
"""Position the label on screen using the given anchor and display size.
474+
475+
:param anchor: One of the predefined anchor constants (e.g., ANCHOR_TOP_LEFT, ANCHOR_CENTER)
476+
:param width: Width of the display in pixels
477+
:param height: Height of the display in pixels
478+
"""
479+
if anchor not in {
480+
LabelBase.ANCHOR_TOP_LEFT,
481+
LabelBase.ANCHOR_TOP_CENTER,
482+
LabelBase.ANCHOR_TOP_RIGHT,
483+
LabelBase.ANCHOR_CENTER_LEFT,
484+
LabelBase.ANCHOR_CENTER,
485+
LabelBase.ANCHOR_CENTER_RIGHT,
486+
LabelBase.ANCHOR_BOTTOM_LEFT,
487+
LabelBase.ANCHOR_BOTTOM_CENTER,
488+
LabelBase.ANCHOR_BOTTOM_RIGHT,
489+
}:
490+
raise ValueError(
491+
"Anchor must be one of: ANCHOR_TOP_LEFT, ANCHOR_TOP_CENTER, ANCHOR_TOP_RIGHT,\n"
492+
"ANCHOR_CENTER_LEFT, ANCHOR_CENTER, ANCHOR_CENTER_RIGHT,\n"
493+
"ANCHOR_BOTTOM_LEFT, ANCHOR_BOTTOM_CENTER, ANCHOR_BOTTOM_RIGHT."
494+
)
495+
496+
self.anchor_point = anchor
497+
self.anchored_position = (
498+
int(anchor[0] * width),
499+
int(anchor[1] * height),
500+
)

0 commit comments

Comments
 (0)