我编写的代码会让我在iOS中的视图放大屏幕并限制我可以缩小的数量。我不希望用户能够缩小开始屏幕。问题是,下面的代码将让我放大,但一旦我在某一点,我无法缩小到开始屏幕。我不确定我做错了什么。
float _currentScale = 1.0f;
public override void ViewDidLoad()
{
base.ViewDidLoad();
UIPinchGestureRecognizer twoFingerPinch = new UIPinchGestureRecognizer();
twoFingerPinch.Delegate = new GestureDelegate();
View.AddGestureRecognizer(twoFingerPinch);
}
class GestureDelegate : UIGestureRecognizerDelegate
{
public override bool ShouldReceiveTouch(UIGestureRecognizer aRecogniser, UITouch aTouch)
{
return true;
}
// Ensure that the pinch, pan and rotate gestures are all recognized simultaneously
public override bool ShouldRecognizeSimultaneously(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer)
{
// if the gesture recognizers views differ, don't recognize
if (gestureRecognizer.View != otherGestureRecognizer.View)
return false;
// if either of the gesture recognizers is a long press, don't recognize
if (gestureRecognizer is UILongPressGestureRecognizer || otherGestureRecognizer is UILongPressGestureRecognizer)
return false;
return true;
}
}
void ScaleScreen(UIPinchGestureRecognizer gestureRecognizer)
{
AdjustAnchorPointForGestureRecognizer(gestureRecognizer);
if (gestureRecognizer.State == UIGestureRecognizerState.Began || gestureRecognizer.State == UIGestureRecognizerState.Changed)
{
float minScale = 1.0f;
float maxScale = 3.0f;
float zoomSpeed = .5f;
float deltaScale = (float)gestureRecognizer.Scale;
deltaScale = ((deltaScale - 1) * zoomSpeed) + 1;
deltaScale = Math.Min(deltaScale, maxScale / _currentScale);
deltaScale = Math.Max(deltaScale, minScale / _currentScale);
_currentScale = deltaScale;
gestureRecognizer.View.Transform *= CGAffineTransform.MakeScale(deltaScale, deltaScale);
// Reset the gesture recognizer's scale - the next callback will get a delta from the current scale.
gestureRecognizer.Scale = 1;
}
}
void AdjustAnchorPointForGestureRecognizer(UIGestureRecognizer gestureRecognizer)
{
if (gestureRecognizer.State == UIGestureRecognizerState.Began)
{
var image = gestureRecognizer.View;
var locationInView = gestureRecognizer.LocationInView(image);
var locationInSuperview = gestureRecognizer.LocationInView(image.Superview);
image.Layer.AnchorPoint = new CGPoint(locationInView.X / image.Bounds.Size.Width, locationInView.Y / image.Bounds.Size.Height);
image.Center = locationInSuperview;
}
}
答案 0 :(得分:0)
我会将这个条件添加到ScaleScreen
void ScaleScreen(UIPinchGestureRecognizer gestureRecognizer)
{
AdjustAnchorPointForGestureRecognizer(gestureRecognizer);
if (gestureRecognizer.State == UIGestureRecognizerState.Began || gestureRecognizer.State == UIGestureRecognizerState.Changed)
//...
else {
if (gestureRecognizer.View.Transform.xx < 1)
UIView.Animate(0.4, () => {
gestureRecognizer.View.Transform = CGAffineTransform.MakeIdentity();
}, null);
}
}
}