import React, { useState } from "react"; import { Text, View } from "@tarojs/components"; import { Button } from "@nutui/nutui-react-taro"; interface IImagePreview { children: React.ReactNode; } export default function ImagePreview(props: IImagePreview) { const { children } = props; const [scale, setScale] = useState(0.5); // 缩放比例 const [touchInfo, setTouchInfo] = useState({ startDistance: 0, startScale: 0.5, }); // 触摸信息 const [position, setPosition] = useState({ x: 0, y: -(29.7 * 37.8 * 0.5) }); // 当前位置 const [startPosition, setStartPosition] = useState({ x: 0, y: 0 }); // 起始位置 // 放大 const zoomIn = () => { setScale((prev) => Math.min(prev + 0.1, 3)); // 最大放大到3倍 }; // 缩小 const zoomOut = () => { setScale((prev) => Math.max(prev - 0.1, 0.5)); // 最小缩小到0.5倍 }; // 重置缩放 const resetZoom = () => { setScale(0.5); setPosition({ x: 0, y: -(29.7 * 37.8 * 0.5) }); // 重置位置 }; // 计算两点间距离 const getDistance = (touches: any) => { const dx = touches[0].clientX - touches[1].clientX; const dy = touches[0].clientY - touches[1].clientY; return Math.sqrt(dx * dx + dy * dy); }; // 处理触摸开始事件 const handleTouchStart = (e: any) => { const touches = e.touches; if (touches.length === 2) { // 双指触摸,记录初始距离和当前缩放值 const distance = getDistance(touches); setTouchInfo({ startDistance: distance, startScale: scale, }); } else if (touches.length === 1) { // 单指触摸,记录起始位置 setStartPosition({ x: touches[0].clientX - position.x, y: touches[0].clientY - position.y, }); } }; // 处理触摸移动事件 const handleTouchMove = (e: any) => { const touches = e.touches; e.preventDefault(); // 阻止默认滚动行为 if (touches.length === 2) { // 双指触摸,计算缩放比例 const currentDistance = getDistance(touches); const newScale = touchInfo.startScale * (currentDistance / touchInfo.startDistance); // 限制缩放范围在0.5到3之间 setScale(Math.min(Math.max(0.5, newScale), 3)); } else if (touches.length === 1 && scale > 0.5) { // 单指触摸且已放大,允许拖动 setPosition({ x: touches[0].clientX - startPosition.x, y: touches[0].clientY - startPosition.y, }); } }; // 处理触摸结束事件 const handleTouchEnd = (e: any) => { // 可以在这里添加触摸结束后的处理逻辑 console.log("Touch ended", e); }; return ( {/* 缩放控制按钮 */} {Math.round(scale * 100)}% {/* 预览区域 */} {children} ); }