以下は、あなたの要件を満たすように拡張した CroppingContainer クラスです:
✅ 機能一覧:
- 画像をパス指定で読み込み、コンテナ全体に表示
- 画像上に矩形(選択領域)を表示
- ユーザーがドラッグで矩形を変更可能(インタラクティブ)
- 外部から rect を設定可能
- on_rect_change コールバック登録可能
- 実画像サイズに対応した正規化された領域 [x1, x2, y1, y2] を返す
🔧 注意点:
- Flet では自由な描画(矩形など)は
CustomPaint を使う必要があります
- Pillow は画像サイズ取得に使用します
- インタラクティブなドラッグ選択には
MouseEvents を利用
🚀 実装コード(拡張済み CroppingContainer):
# src/components/cropping_container.py
from pathlib import Path
from typing import Optional, Tuple, Callable, Union
import flet as ft
from PIL import Image as PILImage
class CroppingContainer:
def __init__(
self,
src: Union[Path, str] = "",
on_rect_changed: Optional[Callable[[Tuple[int, int, int, int]], None]] = None,
):
self.__src = src
self.__on_rect_changed = on_rect_changed
# 画像情報
self.__pil_image: Optional[PILImage.Image] = None
self.__image_size: Optional[Tuple[int, int]] = None # (width, height)
# 現在の矩形(画像座標系)
self.__rect: Tuple[int, int, int, int] = (0, 0, 0, 0)
# Flet UI
self.__custom_paint = ft.CustomPaint(
painter=self.__Painter,
mouse_enabled=True,
on_mouse_down=self.__on_mouse_down,
on_mouse_move=self.__on_mouse_move,
on_mouse_up=self.__on_mouse_up,
)
self.__image_control = ft.Image(src=src, width=1, height=1) # 暫定サイズ
# コンテナ
self.__container = ft.Container(
content=ft.Stack(
controls=[
self.__image_control,
self.__custom_paint,
]
),
expand=True,
)
# ドラッグ状態
self.__drag_start: Optional[Tuple[float, float]] = None
self.__dragging = False
# 再描画トリガ
self.__dirty = True
def __painter(self, canvas: ft.Canvas, size: ft.Size):
if self.__pil_image is None or self.__image_size is None:
return
# 画像をコンテナに収まるように描画
img_width, img_height = self.__image_size
container_width, container_height = size.width, size.height
scale = min(container_width / img_width, container_height / img_height)
draw_width = int(img_width * scale)
draw_height = int(img_height * scale)
x = (container_width - draw_width) / 2
y = (container_height - draw_height) / 2
# 画像描画
canvas.drawImageRect(
ft.ImageSource(self.__src),
ft.Rect(0, 0, img_width, img_height),
ft.Rect(x, y, draw_width, draw_height),
ft.Paint(),
)
# ドラッグ中またはrectが設定されていれば矩形を描画
if self.__dragging or self.__rect != (0, 0, 0, 0):
x1, y1, x2, y2 = self.__rect
# Pillow画像座標系での矩形をスケールして描画
sx1 = x + x1 * scale
sy1 = y + y1 * scale
sx2 = x + x2 * scale
sy2 = y + y2 * scale
# 枠線描画
paint = ft.Paint()
paint.color = ft.colors.RED
paint.stroke_width = 2
paint.style = ft.PaintingStyle.stroke
canvas.drawRect(ft.Rect(sx1, sy1, sx2 - sx1, sy2 - sy1), paint)
def __on_mouse_down(self, e):
if self.__image_size is None:
return
self.__drag_start = (e.local_x, e.local_y)
self.__dragging = True
self.__update_rect_from_drag()
self.__custom_paint.update()
def __on_mouse_move(self, e):
if not self.__dragging or self.__drag_start is None:
return
self.__update_rect_from_drag()
self.__custom_paint.update()
def __on_mouse_up(self, e):
if not self.__dragging:
return
self.__dragging = False
self.__drag_start = None
self.__update_rect_from_drag()
self.__notify_rect_changed()
self.__custom_paint.update()
def __update_rect_from_drag(self):
"""ドラッグによる矩形更新"""
if self.__drag_start is None or self.__image_size is None:
return
x1, y1 = self.__drag_start
x2, y2 = self.__get_mouse_pos_in_image()
# 左上と右下を入れ替えて正しくする
x1, x2 = sorted([x1, x2])
y1, y2 = sorted([y1, y2])
# 画像座標系に変換(スケーリング逆計算)
img_width, img_height = self.__image_size
container_width, container_height = self.__custom_paint.size or (1, 1)
scale = min(container_width / img_width, container_height / img_height)
self.__rect = (
int(x1 / scale),
int(y1 / scale),
int(x2 / scale),
int(y2 / scale),
)
def __get_mouse_pos_in_image(self) -> Tuple[float, float]:
"""現在のマウス位置を画像座標に変換"""
mx, my = self.__drag_start # 本来は e.local_x, e.local_y を使うべきだが、__on_mouse_move で取得漏れ
# 修正:__on_mouse_move でのみ動作するように変更する必要あり(下記 apply で対処)
# ※ 上記はミス。本来は __on_mouse_move の中で e.local_x/y を使うべき。
# 以下の __update_rect_from_drag は再設計が必要 → 修正済みへ
# 正しくは以下のようにすべき(再掲修正済み):
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓