我正在尝试在iPad视图上同时创建典型的捏缩放和平移。视图本身包含4个其他子视图。 我遇到的问题是,虽然我可以同时进行缩放和平移,但是平移超出界限,可以将视图移出框架。
我已经尝试了几种平移限制,但它们似乎都只限制Y轴,或X和Y两者,但仅限于未放大的情况。
有什么建议吗?
以下是我用于捏缩放和平移手势的内容:
// for Pan Gesture
- (void) handlePanGestures:(UIPanGestureRecognizer *)recognizer
{
if (recognizer.state != UIGestureRecognizerStateEnded && recognizer.state != UIGestureRecognizerStateFailed)
{
CGPoint translation = [recognizer translationInView:self.view];
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
CGPoint location = [recognizer locationInView:recognizer.view.superview];
recognizer.view.center = location;
// set final position
recognizer.view.center = finalPoint;
[recognizer setTranslation:CGPointZero inView:self.view];
}
}
// for Pinch Gesture
- (void)handlePinches:(UIPinchGestureRecognizer *)gestureRecognizer
{
if([gestureRecognizer state] == UIGestureRecognizerStateBegan)
{
// Reset the last scale, necessary if there are multiple objects with different scales
self.currentScale = [gestureRecognizer scale];
}
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
[gestureRecognizer state] == UIGestureRecognizerStateChanged)
{
CGFloat currentScale = [[[gestureRecognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];
// Constants to adjust the max/min values of zoom
const CGFloat kMaxScale = 2.0;
const CGFloat kMinScale = 1.0;
CGFloat newScale = 1 - (self.currentScale - [gestureRecognizer scale]);
newScale = MIN(newScale, kMaxScale / currentScale);
newScale = MAX(newScale, kMinScale / currentScale);
CGAffineTransform transform = CGAffineTransformScale([[gestureRecognizer view] transform], newScale, newScale);
[gestureRecognizer view].transform = transform;
self.currentScale = [gestureRecognizer scale]; // Store the previous scale factor for the next pinch gesture call
}
}
答案 0 :(得分:0)
试试这个,对我有用!
-(void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)recognizer{
CGRect xRectRef = self.imageView.superview.frame;
CGPoint translation = [recognizer translationInView:self.imageView];
CGPoint xyNew = CGPointMake(self.imageView.frame.origin.x + translation.x, self.imageView.frame.origin.y + translation.y);
if (recognizer.state == UIGestureRecognizerStateChanged ) {
if ( (xyNew.y <= xRectRef.origin.y) &&
(xyNew.y + self.imageView.frame.size.height >= xRectRef.origin.y + xRectRef.size.height) &&
(xyNew.x <= xRectRef.origin.x ) &&
(xyNew.x + self.imageView.frame.size.width >= xRectRef.size.width+xRectRef.origin.x)){
self.imageView.center = CGPointMake(self.imageView.center.x + translation.x,
self.imageView.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.imageView];
}
}
}