我正在开发一个 iOS 应用程序,其中包含一个可扩展和可平移的UIView
. 由于允许用户平移和缩放视图,我确实希望将其保持UIView
在屏幕的边界内。
我在互联网上搜索了很多,但似乎没有真正适合我需要的例子。
下面是我写的平移代码:
private void HandlePan(UIPanGestureRecognizer recognizer)
{
if (recognizer.State != UIGestureRecognizerState.Began &&
recognizer.State != UIGestureRecognizerState.Changed)
return;
var translation = recognizer.TranslationInView(this);
_posX += translation.X;
_posY += translation.Y;
var maxX = (Bounds.Size.Width / 2) * _currentScale;
var maxY = (Bounds.Size.Height / 2) * _currentScale;
// TODO: The min values are wrong
var minX = (Bounds.Size.Width / 2) / _currentScale;
var minY = (Bounds.Size.Height / 2) / _currentScale;
if (_posX > maxX)
_posX = maxX;
else if (_posX < minX)
_posX = minX;
if (_posY > maxY)
_posY = maxY;
else if (_posY < minY)
_posY = minY;
var translatedCenter = new CGPoint(_posX, _posY);
Center = translatedCenter;
recognizer.SetTranslation(CGPoint.Empty, this);
}
我设法让边界只在屏幕的两侧工作。maxX
并且maxY
是正确的。我只是无法弄清楚如何计算正确minX
和minY
值的方法。
下面我添加了一个屏幕录制来显示出了什么问题:
当我尝试拖动到图像的右侧/底部(即minX
和minY
值)时,您可以看到坐标被阻塞(当比例增加 > 1 时甚至更多)。
这个计算有什么问题,或者正确的计算应该是什么?请注意,maxX
并且maxY
完全正常工作。
var minX = (Bounds.Size.Width / 2) / _currentScale;
var minY = (Bounds.Size.Height / 2) / _currentScale;
另一种计算边界的方法也可以是:
int centerPoint = (int)(Bounds.Size.Width / 2);
var minX = centerPoint - ((_currentScale - 1) * centerPoint);
if (_posX < minX)
_posX = minX;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句