|
| 1 | +# SPDX-FileCopyrightText: 2025 Shubham Patel |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +from micropython import const |
| 6 | + |
| 7 | +try: |
| 8 | + from typing import Tuple |
| 9 | +except ImportError: |
| 10 | + pass |
| 11 | + |
| 12 | +# Anchor point constants for anchor method. |
| 13 | +ANCHOR_TOP_LEFT = const((0.0, 0.0)) |
| 14 | +ANCHOR_TOP_CENTER = const((0.5, 0.0)) |
| 15 | +ANCHOR_TOP_RIGHT = const((1.0, 0.0)) |
| 16 | +ANCHOR_CENTER_LEFT = const((0.0, 0.5)) |
| 17 | +ANCHOR_CENTER = const((0.5, 0.5)) |
| 18 | +ANCHOR_CENTER_RIGHT = const((1.0, 0.5)) |
| 19 | +ANCHOR_BOTTOM_LEFT = const((0.0, 1.0)) |
| 20 | +ANCHOR_BOTTOM_CENTER = const((0.5, 1.0)) |
| 21 | +ANCHOR_BOTTOM_RIGHT = const((1.0, 1.0)) |
| 22 | + |
| 23 | + |
| 24 | +def anchor(obj, anchor: Tuple[float, float], width: int, height: int) -> None: |
| 25 | + """Helper to position a display object on screen using a defined anchor point. |
| 26 | +
|
| 27 | + Sets `anchor_point` and `anchored_position` for display elements such as `Label`, |
| 28 | + `Widget`, `AnchoredTileGrid`, or `AnchoredGroup`. |
| 29 | +
|
| 30 | + :param obj: The object to be positioned. Must support `anchor_point` and `anchored_position`. |
| 31 | + :param anchor: One of the predefined anchor constants (e.g. ANCHOR_TOP_LEFT, ANCHOR_CENTER) |
| 32 | + :param width: Width of the display in pixels |
| 33 | + :param height: Height of the display in pixels |
| 34 | + """ |
| 35 | + if not hasattr(obj, "anchor_point") or not hasattr(obj, "anchored_position"): |
| 36 | + raise AttributeError( |
| 37 | + "Object must have both `anchor_point` and `anchored_position` attributes." |
| 38 | + ) |
| 39 | + |
| 40 | + if anchor not in { |
| 41 | + ANCHOR_TOP_LEFT, |
| 42 | + ANCHOR_TOP_CENTER, |
| 43 | + ANCHOR_TOP_RIGHT, |
| 44 | + ANCHOR_CENTER_LEFT, |
| 45 | + ANCHOR_CENTER, |
| 46 | + ANCHOR_CENTER_RIGHT, |
| 47 | + ANCHOR_BOTTOM_LEFT, |
| 48 | + ANCHOR_BOTTOM_CENTER, |
| 49 | + ANCHOR_BOTTOM_RIGHT, |
| 50 | + }: |
| 51 | + raise ValueError( |
| 52 | + "Anchor must be one of: ANCHOR_TOP_LEFT, ANCHOR_TOP_CENTER, ANCHOR_TOP_RIGHT,\n" |
| 53 | + "ANCHOR_CENTER_LEFT, ANCHOR_CENTER, ANCHOR_CENTER_RIGHT,\n" |
| 54 | + "ANCHOR_BOTTOM_LEFT, ANCHOR_BOTTOM_CENTER, ANCHOR_BOTTOM_RIGHT." |
| 55 | + ) |
| 56 | + |
| 57 | + obj.anchor_point = anchor |
| 58 | + obj.anchored_position = ( |
| 59 | + int(anchor[0] * width), |
| 60 | + int(anchor[1] * height), |
| 61 | + ) |
0 commit comments