unityUnity乱七八糟技巧Unity进阶技术

[Unity 3d] 实现拖拽图片缩放尺寸只需要简单3句代码

2019-08-02  本文已影响9人  雨落随风

在本文,笔者将教大家怎么简单的做出运行时图片尺寸缩放功能。

前言:

老板需要拖拽监控播放器左下角能够缩放播放器界面,本以为好难啊,没想到这么简单,做个笔记水上一贴,也分享给大家吧。

实现:

先是UI结构:


然后是关键代码:

    public float min; //最小缩放尺寸与原尺寸比
    public float max; //最大缩放尺寸与原尺寸比
    private Vector2 orignSize; //缓存原始尺寸
    public RectTransform targetRect; //被控制的 图片 
    void Awake()
    {
        orignSize = targetRect.sizeDelta;
    }
    void IDragHandler.OnDrag(PointerEventData eventData) //仅仅实现一个 IDragHandler 接口就行了
    {
        float x = Mathf.Clamp(targetRect.sizeDelta.x + eventData.delta.x, orignSize.x*min, orignSize.x*max);
        //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; //相比于上一句实现了Image 等比缩放,任选一句。
        targetRect.sizeDelta= new Vector2 (x,y);
    }

完整代码:

/*
 * Target RectTransform Pivot 必须是 (0,1)
 */
using UnityEngine;
using UnityEngine.EventSystems;

public class ImageResizer : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IDragHandler
{
    public float min;
    public float max;
    private Vector2 orignSize;
    [SerializeField]
    private RectTransform targetRect;
    [SerializeField]
    private Texture2D cursorHandle; //鼠标

    void Awake()
    {
        orignSize = targetRect.sizeDelta;
    }

    #region  Function Deal with size

    void IDragHandler.OnDrag(PointerEventData eventData)
    {
        float x = Mathf.Clamp(targetRect.sizeDelta.x + eventData.delta.x, orignSize.x*min, orignSize.x*max);
        //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
}

Tips : 完整代码仅仅是增加了鼠标光标的处理哈~

演示:

结语:

不禁感慨,真相往往如此简单!

上一篇下一篇

猜你喜欢

热点阅读