Unity3d实现自由选中框并截图保存功能(一) 自由选中框实现

Unity3d实现自由选中框并截图保存功能(一) 自由选中框实现

前言

我们日常也会经常用到截图功能,这里我们就将截图的功能做入unity开发的程序内。这里我先实现自由选择框的功能。

最终效果

在这里插入图片描述

实现思路

将一个带透明的image节点作为选中框表示;
按下鼠标左键记录选中框起始位置,并将选中框设置在其实位置;

移动鼠标后,根据鼠标位置更新image的宽、高值,已经中心点(Pivot)。

功能实现

UI搭建

UI较简单就是个image节点:

在这里插入图片描述

鼠标按下

这个的话,直接在update函数内监听输入的GetMouseButtonDown即可:

  if (Input.GetMouseButtonDown(0))
        {
    
    
            Vector2 position;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(Canvas, Input.mousePosition, null, out position);
            StartPos = position;
            SelImg.anchoredPosition = position;
        }

这里的重点是将屏幕的坐标转换到canvas的坐标是使用
RectTransformUtility.ScreenPointToLocalPointInRectangle函数来实现。

同步选择框

在鼠标移动的过程中,获取鼠标位置,然后更新选中框的中心点和长宽属性。

if (Input.GetMouseButton(0))
        {
    
    
            Vector2 position;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(Canvas, Input.mousePosition, null, out position);
            SelImg.pivot = new Vector2(position.x >= StartPos.x ? 0 : 1, position.y >= StartPos.y ? 0 : 1);
            SelImg.sizeDelta = new Vector2(Mathf.Abs(position.x - StartPos.x), Mathf.Abs(position.y - StartPos.y));
        }

完成

这个功能是比较简单的,下一篇进行截图保存的功能。

Unity3d实现自由选中框并截图保存功能(二)截图保存功能

猜你喜欢

转载自blog.csdn.net/qq_33789001/article/details/115181846
今日推荐