效果展示:
步骤流程:
1.使用的是UGUI,将下面的脚本拖拽到图片上即可。
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CheckImage : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
{
public float MaxRange = 5f;
public float MinRange = 0.5f;
private Vector3 offPos;
private Vector3 arragedPos;
private bool isEnter = false;
private bool isDrag = false;
void Update()
{
if (!isEnter) return;
if (!isDrag)
{
SetPivotAndPos();
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
transform.localScale += (transform.localScale.x >= MaxRange ? Vector3.zero : Vector3.one * 0.1f);
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
transform.localScale -= (transform.localScale.x <= MinRange ? Vector3.zero : Vector3.one * 0.1f);
}
}
}
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.GetComponent<RectTransform>(), Input.mousePosition, null, out arragedPos))
{
offPos = transform.position - arragedPos;
}
}
public void OnDrag(PointerEventData eventData)
{
transform.position = offPos + Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
transform.position = offPos + Input.mousePosition;
isDrag = false;
}
public void OnPointerEnter(PointerEventData eventData)
{
isEnter = true;
}
public void OnPointerExit(PointerEventData eventData)
{
isEnter = false;
}
private void SetPivotAndPos()
{
float OffsetX = Input.mousePosition.x - transform.position.x;
float OffsetY = Input.mousePosition.y - transform.position.y;
float PivotX = OffsetX / transform.GetComponent<RectTransform>().rect.width / transform.localScale.x;
float PivotY = OffsetY / transform.GetComponent<RectTransform>().rect.height / transform.localScale.y;
transform.GetComponent<RectTransform>().pivot += new Vector2(PivotX, PivotY);
transform.localPosition += new Vector3(OffsetX, OffsetY, 0);
}
}
2.再给图片的父物体添加个Mask遮罩就ok了。