自定義 ImageView 實現了圖片移動、縮放,但手勢滑動時未處理邊界,導致圖片可無限拖拽超出可視區域。
定義常量 FLIP_DISTANCE = 50(可根據螢幕寬度動態調整),在 onTouchEvent 或 GestureDetector 中記錄滑動起點 startX 與當前點 currentX:
startX - currentX > FLIP_DISTANCE → 向左滑動(切換下一張/執行左滑邏輯)currentX - startX > FLIP_DISTANCE → 向右滑動(切換上一張/執行右滑邏輯)// 平移時實時檢查邊界
float dx = currentX - lastX;
float newLeft = imageLeft + dx;
if (newLeft > 0) newLeft = 0; // 左邊界
if (newLeft + imageWidth < viewWidth) newLeft = viewWidth - imageWidth; // 右邊界
imageLeft = newLeft;
invalidate();
FLIP_DISTANCE = screenWidth / 6 等比例適配不同設備。此方案兼容性強,不依賴特定手勢庫,適合自定義 View 精細控制場景。