在网上找了一圈关于拖拽控制UI大小的代码 都没有比较满意的(类似于windows的窗体),索性自己写一个,但是发现还是有点复杂,这个需求暂时被搁置了,故写了个简单版本的,开撸:
先说下前置条件,被放缩的UI描点选了屏幕的正中间:
UI在图中的位置,这个方法比较取巧,如果要做成windows窗体类似 需要计算坐标点 。下图UI以中心点为零点就可以直接使用鼠标在rect上的位置(posx,posy)赋值给UI的width和height,通过控制宽高实现放缩:
代码如下:
float minSizeWidth =50;//最小宽度
float maxSizeWidth=1000;//最大宽度
float minSizeHeight=50;//最小高度
float maxSizeHeight=1000;//最大高度
float sizeWidth;//UI宽
float sizeHeight;//UI高度
float propor;//宽高比例 用来成比例缩放
Vector2 pot;//鼠标 在 Rect上的 POSX 和 POSY
void Start()
{
rt = GetComponent<RectTransform>();//脚本挂在需要放大缩小的UI图层上
propor = rt.rect.width / rt.rect.height;//获取长款的比例
}
public void OnBeginDrag(PointerEventData eventData)
{
//后续增加判断鼠标位置点
}
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rt,
Input.mousePosition, null, out pot))//将鼠标点转化为RECT的位置点
{
rt.sizeDelta = new Vector2(Mathf.Abs(pot.x)*2, Mathf.Abs(pot.x) *
propor*2);//将位置点赋值给UI的长宽 此处取巧因为零点在中心点 鼠标的位置直接可以当UI
//的宽高,后续加了拖动以后这块得改为与UI中心点距离
}
}
public void OnEndDrag(PointerEventData eventData)
{
}
/// <summary>
/// 大小限制
/// </summary>
void SizeRangeLimit()
{
sizeWidth = Mathf.Clamp(rt.rect.width, minSizeWidth, maxSizeWidth);
sizeHeight = Mathf.Clamp(rt.rect.height, minSizeHeight, maxSizeHeight);
rt.sizeDelta = new Vector2(sizeWidth, sizeHeight);
}
void Update()
{
SizeRangeLimit();
}
效果如下:
不过发现windows窗体的一个简单放缩功能自己实现起来都很困难。。。路漫漫其修远兮,写代码之路才刚刚开始。。。