如何在一个背景图上设置点击块
项目过程中遇到一个这样的问题,有一个大的背景图(如下图所示),图上设置好了1,2,3这样的按键快,我们需要给这些无规则的快设置点击事件!
解决思路,首先把图片放到界面中,犹豫不同机型尺寸不同,这个地方需要注意调整界面尺寸:
UIScrollView*scrollView=[[UIScrollView alloc]initWithFrame:SPFrame(0, 0, SPScreen_W, SPScreen_H)]; scrollView.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever; scrollView.bounces=NO; scrollView.showsVerticalScrollIndicator=NO; CGFloat h=SPScreen_W*1056/375.0f; scrollView.contentSize=CGSizeMake(SPScreen_W,h ); UIImageView*bgImageView=[[UIImageView alloc]initWithFrame:SPFrame(0, 0, SPScreen_W, h)]; bgImageView.image=[UIImage imageNamed:@"course_a"]; [scrollView addSubview:bgImageView]; [self.view addSubview:scrollView];
然后我们给背景图添加一个点击的手势
bgImageView.userInteractionEnabled=YES; UITapGestureRecognizer*tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureEvent:)]; [bgImageView addGestureRecognizer:tapGesture];
现在我们需要确定这些点击块的中心,这边当然不要一个一个去测量,作为一个程序员当然要用程序来解决,这边可以在点击手势的事件中直接打印点击的点的坐标,记录下来即可,然后将这些点做一下处理保存到数组points中,处理方法如下
-(NSValue*)changeOriginalPoint:(CGPoint)opoint{ CGFloat w=SPScreen_W; CGFloat h=w*1056.0f/375.0f; CGFloat x=opoint.x*w/375.0f; CGFloat y=opoint.y*h/1056.0f; CGPoint point=CGPointMake(x, y); return [NSValue valueWithCGPoint:point]; }
现在我们需要处理的就是,判断我们点击的点是否在点击块中间
首先我们要利用上面点击块的中心点来设计一个点击区域
-(CGRect)center:(CGPoint)center expandArea:(CGFloat)number{ CGRect rect=SPFrame(center.x-number, center.y-number, number*2, number*2); return rect; }
然后实现点击手势事件,判断当前点击的点是否在点击块中即可
-(void)tapGestureEvent:(UITapGestureRecognizer*)sender{ CGPoint point = [sender locationInView:sender.view]; if([self directPoint:point]>=0&&[self directPoint:point]<32){ ActivityViewController*AVC=[[ActivityViewController alloc]init]; NSInteger n=[self directPoint:point]; AVC.message=[CourseMessage yy_modelWithDictionary:self.courseList[n]]; [self.navigationController pushViewController:AVC animated:YES]; } } -(NSInteger)directPoint:(CGPoint)point{ NSInteger n=9999; 循环块:0-self.points { CGPoint opoint=[self.points[i] CGPointValue]; CGRect frame=[self center:opoint expandArea:16]; if(CGRectContainsPoint(frame, point)){ n=I; break; } } return n; }