Pinch2Zoom
using UnityEngine;
using UnityEngine.UI;
public class PinchToZoom : MonoBehaviour
{
public float minScale = 0.5f; // Minimum scale of the image
public float maxScale = 3f; // Maximum scale of the image
private Vector2 initialTouch1;
private Vector2 initialTouch2;
private float initialDistance;
private Vector3 initialScale;
void Update()
{
// Check for two touches
if (Input.touchCount == 2)
{
Touch touch1 = Input.GetTouch(0);
Touch touch2 = Input.GetTouch(1);
// Handle the initial touch points
if (touch1.phase == TouchPhase.Began || touch2.phase == TouchPhase.Began)
{
initialTouch1 = touch1.position;
initialTouch2 = touch2.position;
initialDistance = Vector2.Distance(initialTouch1, initialTouch2);
initialScale = transform.localScale;
}
// Handle the pinch gesture
else if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved)
{
Vector2 currentTouch1 = touch1.position;
Vector2 currentTouch2 = touch2.position;
float currentDistance = Vector2.Distance(currentTouch1, currentTouch2);
// Calculate the scale factor
float scaleFactor = currentDistance / initialDistance;
// Apply the scale factor
Vector3 newScale = initialScale * scaleFactor;
// Clamp the scale to min and max values
newScale.x = Mathf.Clamp(newScale.x, minScale, maxScale);
newScale.y = Mathf.Clamp(newScale.y, minScale, maxScale);
newScale.z = 1f; // Ensure the Z scale remains unchanged
// Apply the new scale to the image
transform.localScale = newScale;
}
}
}
}