Pinch zoom on UI

Hi everybody, I use this script made by unity for pinch zoom, but I can’t zoom in or out the UI in my canvas. How could I do please ?

3 Answers

3

Hey. Hope this works for you:

using UnityEngine;

public class PinchZoom : MonoBehaviour
{
    public Canvas canvas; // The canvas
    public float zoomSpeed = 0.5f;        // The rate of change of the canvas scale factor
    
    void Update()
    {
        // If there are two touches on the device...
        if (Input.touchCount == 2)
        {
            // Store both touches.
            Touch touchZero = Input.GetTouch(0);
            Touch touchOne = Input.GetTouch(1);

            // Find the position in the previous frame of each touch.
            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

            // Find the magnitude of the vector (the distance) between the touches in each frame.
            float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

            // Find the difference in the distances between each frame.
            float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

            // ... change the canvas size based on the change in distance between the touches.
            canvas.scaleFactor -= deltaMagnitudeDiff * zoomSpeed;

            // Make sure the canvas size never drops below 0.1
            canvas.scaleFactor = Mathf.Max(canvas.scaleFactor, 0.1f);
        }
    }
}

I just slightly edited the original tutorial source code. Remember to assign the canvas in the inspector. You may have to play around with the numbers :wink:

Thanks it works like a charm.

This code is just zooming. Is it possible to add Pan to this code?

It works perfectly for me but it does not respect the boundaries of my device display. It moves out of the UI while dragging. Do you have any suggestion how to fix this?

This code is just zooming.
Is it possible to add Pan to this code?

It works perfectly for me but it does not respect the boundaries of my device display. It moves out of the UI while dragging. Do you have any suggestion how to fix this?

Yea what @TheDJBuntin says. To further what you said though, yes a button is a gameObject. everything that exists in the scene's hierarchy is a gameObject. A button a script on that gameObject which gives the game object the ability to be a button, ie, onClick events. So when someone says a gameObject, in general it means "a thing" that exists in the scene.