在移动端手指捏合UI缩放
为防止在ScrollRect捏合时移动,在手指移动时屏蔽了该组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TouchZoom : MonoBehaviour
{
public RectTransform curRect; //当前缩放对象
public RectTransform baseRect; //scrollect size
public ScrollRect scrollRect; //ScrollRect
public float fRate = 1000f; //缩放因子 1000像素=0.01
public float maxSize = 1.5f; //放大的最大size
private Touch oldTouch1;
private Touch oldTouch2;
private Touch newTouch1;
private Touch newTouch2;
private void Update()
{
//没有触摸
if (Input.touchCount <= 1)
{
if (!scrollRect.isActiveAndEnabled)
{
scrollRect.enabled = true;
}
return;
}
if (Input.touchCount >= 2)
{
if (scrollRect.isActiveAndEnabled)
{
scrollRect.enabled = false;
}
}
else
{
scrollRect.enabled = true;
}
//多点触摸, 放大缩小
newTouch1 = Input.GetTouch(0);
newTouch2 = Input.GetTouch(1);
//第2点刚开始接触屏幕, 只记录,不做处理
if (newTouch2.phase == TouchPhase.Began)
{
oldTouch2 = newTouch2;
oldTouch1 = newTouch1;
return;
}
//计算手指与上次的距离差
float offset = Vector2.Distance(newTouch1.position, newTouch2.position) - Vector2.Distance(oldTouch1.position, oldTouch2.position);
//计算缩放
float scaleFactor = offset / fRate;
//m_scrollRect.enabled = scaleFactor == 0;
//获取地图当前的缩放比例
Vector3 localScale = curRect.localScale;
//计算实际显示区域的宽和高
float areaWidth = baseRect.sizeDelta.x + UIManager.canvasSize.x;//此处未ui根 canvas实际大小
float areaHight = baseRect.sizeDelta.y + UIManager.canvasSize.y;
//根据实际大小计算缩放的最小比例 去缩放较大的
float WidthMin = Mathf.Max(areaWidth / curRect.rect.width, areaHight / curRect.rect.height) - localScale.x;
//最大的放大比例
float WidthMax = maxSize - localScale.x;
scaleFactor = Mathf.Clamp(scaleFactor, WidthMin, WidthMax);
Zoom(curRect.rect.width, curRect.rect.height, areaWidth, areaHight, localScale.x + scaleFactor);
//记录当前点
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}
public void Zoom(float width, float height, float curWith, float curHeight, float scale)
{
float Map_X = curRect.anchoredPosition.x;
float Map_Y = curRect.anchoredPosition.y;
// 计算当前比例边界的极限值
float Limit_X = (width * scale - curWith) / 2f;
float Limit_Y = (height * scale - curHeight) / 2f;
if (Map_X < 0 && Map_Y < 0)
{
Limit_X = Limit_X * -1;
Limit_Y = Limit_Y * -1;
}
else if (Map_X > 0 && Map_Y < 0)
{
Limit_Y = Limit_Y * -1;
}
else if (Map_X < 0 && Map_Y > 0)
{
Limit_X = Limit_X * -1;
}
bool isRemove = false;
if (Mathf.Abs(Map_X) > Mathf.Abs(Limit_X))
{
Map_X = Limit_X;
isRemove = true;
}
if (Mathf.Abs(Map_Y) > Mathf.Abs(Limit_Y))
{
Map_Y = Limit_Y;
isRemove = true;
}
if (isRemove)
{
curRect.anchoredPosition = new Vector3(Map_X, Map_Y, 0);
}
Vector3 Scale = new Vector3(scale, scale, scale);
curRect.localScale = Scale;
}
}