ZoomImage.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using UnityEngine;
  2. public class ZoomImage : MonoBehaviour
  3. {
  4. public Transform targetImage; // 需要缩放和移动的图片
  5. public float minScale = 0.5f; // 最小缩放比例
  6. public float maxScale = 3.0f; // 最大缩放比例
  7. public float sensitivity = 0.01f; // 缩放灵敏度
  8. private Vector2[] lastTouchPositions = new Vector2[2];
  9. private float initialDistance;
  10. private bool isZooming = false; // 是否正在缩放
  11. private Vector3 initialImagePosition; // 图片的初始位置
  12. private Vector2 initialTouchPosition; // 单指触摸的初始位置
  13. void Update()
  14. {
  15. HandleZoom();
  16. HandleMove();
  17. }
  18. void HandleZoom()
  19. {
  20. if (Input.touchCount == 2)
  21. {
  22. Touch touch1 = Input.GetTouch(0);
  23. Touch touch2 = Input.GetTouch(1);
  24. if (touch1.phase == TouchPhase.Began || touch2.phase == TouchPhase.Began)
  25. {
  26. // 记录初始触摸位置
  27. lastTouchPositions[0] = touch1.position;
  28. lastTouchPositions[1] = touch2.position;
  29. initialDistance = Vector2.Distance(lastTouchPositions[0], lastTouchPositions[1]);
  30. isZooming = true;
  31. }
  32. else if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved)
  33. {
  34. // 计算当前触摸位置
  35. Vector2[] currentTouchPositions = new Vector2[2];
  36. currentTouchPositions[0] = touch1.position;
  37. currentTouchPositions[1] = touch2.position;
  38. // 计算当前触摸点之间的距离
  39. float currentDistance = Vector2.Distance(currentTouchPositions[0], currentTouchPositions[1]);
  40. // 计算缩放比例
  41. float scaleFactor = currentDistance / initialDistance;
  42. // 应用缩放
  43. Vector3 newScale = targetImage.localScale * scaleFactor;
  44. newScale.x = Mathf.Clamp(newScale.x, minScale, maxScale);
  45. newScale.y = Mathf.Clamp(newScale.y, minScale, maxScale);
  46. newScale.z = 1; // 保持 Z 轴不变
  47. targetImage.localScale = newScale;
  48. // 更新初始距离
  49. initialDistance = currentDistance;
  50. }
  51. else if (touch1.phase == TouchPhase.Ended || touch2.phase == TouchPhase.Ended)
  52. {
  53. isZooming = false;
  54. }
  55. }
  56. }
  57. void HandleMove()
  58. {
  59. if (Input.touchCount == 1 && !isZooming)
  60. {
  61. Touch touch = Input.GetTouch(0);
  62. if (touch.phase == TouchPhase.Began)
  63. {
  64. // 记录初始触摸位置和图片位置
  65. initialTouchPosition = touch.position;
  66. initialImagePosition = targetImage.position;
  67. }
  68. else if (touch.phase == TouchPhase.Moved)
  69. {
  70. // 计算触摸点的位移
  71. Vector2 touchDelta = touch.position - initialTouchPosition;
  72. // 将屏幕坐标转换为世界坐标
  73. Vector3 worldDelta = Camera.main.ScreenToWorldPoint(new Vector3(touchDelta.x, touchDelta.y, 0)) -
  74. Camera.main.ScreenToWorldPoint(Vector3.zero);
  75. // 更新图片位置
  76. targetImage.position = initialImagePosition + worldDelta;
  77. }
  78. }
  79. }
  80. }