簡體   English   中英

裁剪UIImageView和手勢識別器

[英]Crop UIImageView and gesture recognizer

我有ImageView,我想以此來圈出:

self.contentMode = UIViewContentModeScaleAspectFill;
self.layer.cornerRadius = self.bounds.size.height / 2.0;
self.layer.masksToBounds = YES;

然后我向其中添加了手勢識別器,但是它會在裁剪區域觸發。

如何避免在種植區域開火?

遮罩圖像的一種更通用,更靈活的方法是使用CAShapeLayer。 您可以創建任何形狀(包括圓形)以用作蒙版。 通過使用這種方法來裁剪圖像視圖而不是使用cornerRadius ,您可以檢查接觸點是否在圖層的路徑( UIBezierPath )內。 UIImageView子類中,添加以下代碼以創建蒙版,並在.h文件中創建形狀屬性。

self.shape = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = self.shape.CGPath;
self.layer.mask = shapeLayer;

在控制器中,添加點擊手勢識別器,並在其action方法中使用此代碼,

-(void)handleTap:(UITapGestureRecognizer *) tapper {
    CGPoint touchPoint = [tapper locationInView:tapper.view];
    if ([self.imageView.shape containsPoint:touchPoint]) {
        NSLog(@"touched");
        // do what you want with the touch here
    }
}
  1. 設置您的類符合UIGestureRecognizerDelegate
  2. 將手勢代表設置為自我
  3. 然后使用此委托來確定是否要觸發

    -(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

范例程式碼

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
CGPoint  touchPoint = [touch locationInView:self.imageview];
if (CGRectContainsPoint(self.imageview.bounds, touchPoint)) {
    CGFloat centerX = CGRectGetMidX(self.imageview.bounds);
    CGFloat centerY = CGRectGetMidY(self.imageview.bounds);
    CGFloat radius2 = pow((touchPoint.x -centerX),2)+ pow((touchPoint.y - centerY), 2);
    if (radius2 < pow(CGRectGetWidth(self.imageview.frame)/2, 2)) {
        return YES;
    }
}
return NO;}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM