Ugui 实现拖拽图片缩放尺寸
作者:互联网
原文链接:https://www.jianshu.com/p/b66d0120e4a1
如果想通过拖动图片的右下角控制图片的缩放,那么需要在目标图片的右下角创建一个图片并作为目标图片的子物体,然后把右下角图片的锚点设置为右下角对齐,最后把功能脚本挂载在右下角图片的物体上,通过拖动它控制目标图片缩放尺寸,如下图:
脚本如下:
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 中心点
/// </summary>
public enum PivotType
{
leftTop=0,
center,
rightBottom,
}
public class ImageResizer : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IDragHandler
{
public float minRatio; //最小缩放尺寸与原尺寸比
public float maxRatio; //最大缩放尺寸与原尺寸比
private Vector2 orignSize; //缓存原始尺寸
public RectTransform targetRect; //被控制的 图片
[SerializeField]
private Texture2D cursorHandle; //鼠标
public PivotType pivotType;
void Awake()
{
orignSize = targetRect.sizeDelta;
SetPivot(pivotType);
}
#region Function Deal with size
void SetPivot(PivotType pivotType)
{
switch (pivotType)
{
case PivotType.leftTop:
targetRect.pivot = new Vector2(0, 1);
break;
case PivotType.center:
targetRect.pivot = new Vector2(0.5f, 0.5f);
break;
case PivotType.rightBottom:
targetRect.pivot = new Vector2(1, 0);
break;
}
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
float x = Mathf.Clamp(targetRect.sizeDelta.x + eventData.delta.x, orignSize.x * minRatio, orignSize.x * maxRatio);
//float y = Mathf.Clamp(targetRect.sizeDelta.y - eventData.delta.y, orignSize.y*min, orignSize.y*max);
float y = x / targetRect.sizeDelta.x * targetRect.sizeDelta.y; //等比缩放
targetRect.sizeDelta = new Vector2(x, y);
}
// 重置Target 尺寸
public void ResetSize()
{
targetRect.sizeDelta = orignSize;
}
#endregion
#region Cursor Behaviours
public void OnPointerEnter(PointerEventData eventData)
{
Cursor.SetCursor(cursorHandle, Vector2.zero, CursorMode.Auto);
}
public void OnPointerExit(PointerEventData eventData)
{
SetDefaultCursor();
}
private static void SetDefaultCursor()
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
private void OnDisable()
{
SetDefaultCursor();
}
private void OnDestroy()
{
SetDefaultCursor();
}
#endregion
}
标签:targetRect,缩放,void,拖拽,orignSize,Ugui,Vector2,public,sizeDelta 来源: https://blog.csdn.net/lizhenxiqnmlgb/article/details/100153412