iOS点击图片不同的区域添加相应的响应事件

首先了解一下官方的API说明:

  1. /* Return true if point' is contained inrect', false otherwise. */
    CG_EXTERN bool CGRectContainsPoint(CGRect rect, CGPoint point)
  1. // individual UIGestureRecognizer subclasses may provide subclass-specific location information. see individual subclasses for details
  • (CGPoint)locationInView:(nullable UIView*)view; // a generic single-point location for the gesture. usually the centroid of the touches involved

方案:通过给图片添加点击手势,区分有效范围,实现不同位置的点击响应
例子:

- (void)tap:(UIGestureRecognizer *)ges {
    CGPoint location = [ges locationInView:self.view];
    NSLog(@"---x:%f   y:%f",location.x,location.y);
    
    for (AreaModel *areaModel in AreaList) {
        CGFloat originX = floor(self.view.width * areaModel.hotAreaX.floatValue);
        CGFloat originY = floor(self.view.height * areaModel.hotAreaY.floatValue);
        CGFloat width = floor(self.view.width * areaModel.hotAreaWidth.floatValue);
        CGFloat height = floor(self.view.height * areaModel.hotAreaHeight.floatValue);
        CGRect frame = CGRectMake(originX, originY, width, height);
        if(CGRectContainsPoint(frame, location)){
            NSLog(@"点中了-------------");
         
            return;
        }
    }
}

你可能感兴趣的:(iOS点击图片不同的区域添加相应的响应事件)