How to create a zoomable canvas image in Unity for mobile without scaling the main camera?
I have GameObject with Scroll Rect and Rect Mask in my canvas and there is an image in it. I want to zoom in and zoom out of that image. However I don't want to scale Main Camera because there will be other objects in the screen that I don't want to zoom. I searched it but all the tutorials are doing that by scaling Main Camera.
This video is exactly what I want but it doesn't work in android. https://www.youtube.com/watch?v=BFX3FpUnoio&ab_channel=JasonWeimann
This is the script in that video which is added to "image". I tried to modify it but I messed it up. How can I make it work in mobile?
using UnityEngine;
using UnityEngine.EventSystems;
public class UIZoomImage : MonoBehaviour, IScrollHandler
{
private Vector3 initialScale;
[SerializeField]
private float zoomSpeed = 0.1f;
[SerializeField]
private float maxZoom = 10f;
private void Awake()
{
initialScale = transform.localScale;
}
public void OnScroll(PointerEventData eventData)
{
var delta = Vector3.one * (eventData.scrollDelta.y * zoomSpeed);
var desiredScale = transform.localScale + delta;
desiredScale = ClampDesiredScale(desiredScale);
transform.localScale = desiredScale;
}
private Vector3 ClampDesiredScale(Vector3 desiredScale)
{
desiredScale = Vector3.Max(initialScale, desiredScale);
desiredScale = Vector3.Min(initialScale * maxZoom, desiredScale);
return desiredScale;
}
}
Your answer
Follow this Question
Related Questions
Scaling giant images as 2D Sprite 0 Answers
Images are "stretched" when building for web 0 Answers
Fullscreen canvas shrinks to half size in build only? 0 Answers
Positioning object on mouse position 0 Answers
Scale all things inside UI canvas 0 Answers