为解决UGUI中 ScrollView 下的Content 实现以鼠标为中心的缩放功能(本来是想以鼠标为中心 但实现后 在编辑器中和发布后的效果有差别 能用)
参考了网上的算法 但其代码取值、赋值、时机等都有问题,自己改了后能用了
----------改进------------
magCoe用来调节缩放速度。
/// <summary>
/// 以鼠标位置为中心 缩放对象
/// </summary>
/// <param name="zoomCoe"></param>
void ScaleTargetAtCenterPos(float zoomCoe, Vector3 centerScreenPos)
{
if ((zoomCoe > 0 && transform.localScale.y >= 1) || (zoomCoe < 0 && transform.localScale.y <= 0.35f) || zoomCoe == 0) return;
Vector2 pivot = GetComponent<RectTransform>().pivot;
float width = GetComponent<RectTransform>().rect.width;
float height = GetComponent<RectTransform>().rect.height;
centerWorldPos = uiCamera.ScreenToWorldPoint(centerScreenPos);
targetLocalPos = transform.parent.worldToLocalMatrix.MultiplyPoint(centerWorldPos);
float delX = targetLocalPos.x - transform.localPosition.x;
float delY = targetLocalPos.y - transform.localPosition.y;
float pivotDelX = delX / (width * transform.localScale.x);
float pivotDelY = delY / (height * transform.localScale.y);
transform.localPosition += new Vector3(delX, delY, 0);
pivot += new Vector2(pivotDelX, pivotDelY);
GetComponent<RectTransform>().pivot = new Vector2(Mathf.Clamp(pivot.x, 0, 1), Mathf.Clamp(pivot.y, 0, 1));
if (zoomCoe > 0)
transform.localScale += Vector3.one * magCoe;
else if (zoomCoe < 0)
transform.localScale += Vector3.one * -magCoe;
}