前言
我们日常也会经常用到截图功能,这里我们就将截图的功能做入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));
}
完成
这个功能是比较简单的,下一篇进行截图保存的功能。