`public class CloneImage : MonoBehaviour, IPointerClickHandler,IBeginDragHandler,IDragHandler
{
// Start is called before the first frame update
private float fingerX = 0;
private float fingerY = 0;
private float DistanceNow = 0;
private float DistanceLast = 0;
private float MaxDistance = 3;
private float MinDistance = 1;
private float TheDistance = 2;
public Image mask;
RectTransform rt;
Vector3 offset = Vector3.zero;
void Start()
{
rt = GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
FingerControl();
}
public void OnPointerClick(PointerEventData eventData)
{
if (Input.touchCount <=1)
{
eventData.pointerPress.gameObject.SetActive(false);
mask.gameObject.SetActive(false);
}
}
void FingerControl() //两个手指放大图片的方法
{
if (Input.touchCount > 1 && (Input.
GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))
{
DistanceNow = Vector2.Distance(Input.GetTouch(0).position, Input.GetTouch(1).position); //获得两个手指的坐标点距离
if (DistanceNow > DistanceLast)
{
TheDistance += Vector2.Distance(Input.GetTouch(0).deltaPosition, Input.GetTouch(1).deltaPosition) * 0.01F; //图像尺寸的变化量
}
else
{
TheDistance -= Vector2.Distance(Input.GetTouch(0).deltaPosition, Input.GetTouch(1).deltaPosition) * 0.01F; //图像尺寸的变化量
}
DistanceLast = DistanceNow; //实时更新两个手指间距
if (TheDistance <= MinDistance) //限定最小尺寸
{
TheDistance = MinDistance;
}
if (TheDistance >= MaxDistance) //限定最大尺寸
{
TheDistance = MaxDistance;
}
transform.localScale = new Vector3(TheDistance, TheDistance, 0);
}
}
public void OnBeginDrag(PointerEventData eventData)
{
//if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.enterEventCamera, out Vector3 globalMousePos))
//{
// //计算偏移量
// offset = rt.position - globalMousePos;
//}
}
public void OnDrag(PointerEventData eventData)
{
//if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out Vector3 globalMousePos))
//{
// // 加上偏移量保证相对位置不变
// rt.position = globalMousePos + offset;
//}
}
}
UI双指缩放代码
最新推荐文章于 2022-02-28 14:11:03 发布