在UIView Mask中限制UIPanGestureRecognizer

时间:2016-02-29 09:18:21

标签: ios objective-c uiview uipangesturerecognizer

我使用 UIBezierPath 按照以下方式屏蔽UIView(240 * 240)的tringular形状:

path = [UIBezierPath new];
[path moveToPoint:(CGPoint){0, 240}];
[path addLineToPoint:(CGPoint){120,0}];
[path addLineToPoint:(CGPoint){240,240}];
[path addLineToPoint:(CGPoint){0,240}];
[path closePath];

CAShapeLayer *mask = [CAShapeLayer new];
mask.frame = self.viewShape.bounds;
mask.path = path.CGPath;
self.viewShape.layer.mask = mask;

enter image description here

在上面的图像中,三角形区域是掩模。现在我有了#34; Coca-Cola"只能用三角形面罩移动。因此,我已将 UIPanGestureRecognizer 应用于 UIIMageView 并以下列方式限制其框架。

- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint touchLocation = [gestureRecognizer locationInView:self.viewShape];

    CGRect boundsRect;

    BOOL isInside = [path containsPoint:CGPointMake(self.innerView.center.x, self.innerView.center.y)];
    NSLog(@"value:%d",isInside);
    if (isInside) {
        NSLog(@"inside");
        self.innerView.center = touchLocation;
    }else{
        NSLog(@"outside");
    }
}

我上面的 if 条件成功执行,但当控件进入 else 条件时,我无法将我的ImageView拖回到遮罩框架内。

所以,我的问题是当 else 阻止(外部)调用时,我应该能够在Mask的框架内再次拖动imageView。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

保存对imageview最后一个中心的引用是实现此目的的一种方法。 在您的customView中;

CGPoint lastValidCenter; //initially it is the center of imageview;

并在代码中

NSLog(@"value:%d",isInside);
    if (isInside) {
        NSLog(@"inside");
        self.innerView.center = touchLocation;
        lastValidCenter = self.innerView.center;
    }else{
        NSLog(@"outside");
        self.innerView.center = lastValidCenter;
    }

答案 1 :(得分:0)

您的计算存在问题。您需要做的是检查UIImageView的左上角和右上角是否包含UIBezirePath实例的包含点。 之所以如此,因为当图像移动时,这两个角都会先尝试出去。所以只需检查一下,你就可以获得所需的输出。

BOOL isInside = [path containsPoint:CGPointMake(CGRectGetMinX(self.innerView.bounds), CGRectGetMinY(self.innerView.bounds))];
isInside = isInside || [path containsPoint:CGPointMake(CGRectGetMaxX(self.innerView.bounds), CGRectGetMinY(self.innerView.bounds))];
if (isInside) {
//Move your UIImageView
}
else {
//Don't move
}

答案 2 :(得分:0)

我修改了Meth的部分代码。代码如下:

self.innerView.center = touchLocation;
BOOL isInside = [path containsPoint:CGPointMake(self.innerView.center.x, self.innerView.center.y)];
if (isInside) {
        NSLog(@"inside");
        self.innerView.center = touchLocation;
        lastValidCenter = self.innerView.center;
    }else{
        NSLog(@"outside");
        self.innerView.center = lastValidCenter;
    }