using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
public class PictureZoomForWindows : MonoBehaviour, IDragHandler, IPointerDownHandler
{
#region Zoom
///
/// 得到图片
///
public RectTransform image;
///
/// 是否有两只手指按下
///
private bool isTwoTouch = false;
[SerializeField, Header("缩放")]
float minExtend = 0.5f;
[SerializeField, Header("扩大")]
float maxExtend = 10.0f;
#endregion
#region Move
// 当前面板
[SerializeField]
private RectTransform panelRectTransform;
// 父节点,这个最好是UI父节点,因为它的矩形大小刚好是屏幕大小
[SerializeField]
private RectTransform parentRectTransform;
#endregion
[SerializeField]
Image images;
[SerializeField]
bool isScrollWheel = false;
[SerializeField]
private float mouseExtendScale = 0.0f;
[SerializeField, Header("鼠标缩放计算")]
bool scrollScaleCal = false;
[SerializeField, Range(1, 10)]
int scaleFactor = 3;
Vector3 offsetPos; //存储按下鼠标时的图片-鼠标位置差
void Awake()
{
panelRectTransform = transform.parent as RectTransform;
parentRectTransform = panelRectTransform.parent as RectTransform;
}
// Use this for initialization
void Start()
{
}
private void LateUpdate()
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
MouseExtend();
#endif
}
void MouseExtend()
{
if (isScrollWheel)
{
float scrollValue = Input.GetAxis("Mouse ScrollWheel");
if (scrollValue < 0)
{
if (mouseExtendScale > 0)
{
mouseExtendScale = 0;
}
mouseExtendScale += scrollValue * scaleFactor;
scrollScaleCal = true;
#if UNITY_EDITOR
Debug.Log("Zoom Out:\t" + mouseExtendScale);
#endif
}
//-Zoom In-//
if (scrollValue > 0)
{
if (mouseExtendScale < 0)
{
mouseExtendScale = 0;
}
mouseExtendScale += scrollValue * scaleFactor;
scrollScaleCal = true;
#if UNITY_EDITOR
Debug.Log("Zoom In:\t" + scrollValue);
#endif
}
PictureScale();
}
}
///
/// 图片缩放核心脚本 Windows 平台放大缩小
///
/// 缩放距离
private void PictureScale()
{
if (scrollScaleCal)
{
//当前图片的缩放
Vector3 curImageScale = new Vector3(image.localScale.x, image.localScale.y, 1);
//两根手指上一帧和这帧之间的距离差
//因为100个像素代表单位1,把距离差除以100看缩放几倍
float changeScaleDistance = mouseExtendScale / 100;
#if UNITY_EDITOR
Debug.Log("ChangeScaleDistance:\t" + changeScaleDistance);
#endif
//因为缩放 Scale 是一个Vector3,所以这个代表缩放的Vector3的值就是缩放的倍数
Vector3 changeScale = new Vector3(changeScaleDistance, changeScaleDistance, 0);
//图片的缩放等于当前的缩放加上 修改的缩放
image.localScale = curImageScale + changeScale;
//控制缩放级别
image.localScale = new Vector3(Mathf.Clamp(image.localScale.x, minExtend, maxExtend), Mathf.Clamp(image.localScale.y, minExtend, maxExtend), 1);
scrollScaleCal = false;
}
}
///
/// 将鼠标的位置坐标进行钳制,然后加上位置差再赋值给图片position
///
///
public void OnDrag(PointerEventData eventData)
{
panelRectTransform.position = new Vector3(Mathf.Clamp(Input.mousePosition.x, 0, Screen.width), Mathf.Clamp(Input.mousePosition.y, 0, Screen.height), 0) + offsetPos;
}
///
/// 鼠摁下获取偏差位置
///
///
public void OnPointerDown(PointerEventData eventData)
{
offsetPos = panelRectTransform.position - Input.mousePosition;
}
}