自定义视图点击区域

来源:互联网 发布:淘宝免费数据分析工具 编辑:程序博客网 时间:2024/05/18 02:36

自定义视图点击区域

大家都知道,一个按钮或者视图的有效点击区域是一个长方形,包括圆形头像,如何让这些圆形,或者不规则图形或者按钮的有效点击区域只在圆形范围内或者只在不规则图形内呢?

效果如下:
这里写图片描述
图中,灰色为点击区域,橘黄色的为按钮矩形区域。

答案是可以的,通过这个方法就可以做到。

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event 

我们只需要重写函数就可以做到,是不是在有效点击区域。
判断是不是在

- (BOOL)containsPoint:(CGPoint)point;

一下是我自定义的一个圆形按钮,ViewController整个代码如下

#import "ViewController.h"#import "MyBtn.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    MyBtn *mybtn = [[MyBtn alloc] init];    mybtn.frame =(CGRect){{40,40},{300,300}};    self.view.backgroundColor = [UIColor whiteColor];    [self.view addSubview:mybtn];    mybtn.backgroundColor = [UIColor orangeColor];    [mybtn addTarget:self action:@selector(btnclick:) forControlEvents:UIControlEventTouchUpInside];}- (void)btnclick:(id)btn{    NSLog(@"test");}@end

自定义的圆形按钮代码如下。

#import "MyBtn.h"@implementation MyBtn-(void)drawRect:(CGRect)rect{      CGRect bounds = self.bounds;    CGPoint center;    center.x = bounds.origin.x +bounds.size.width/2.0;    center.y = bounds.origin.y +bounds.size.height/2.0;    float radius = (MIN(bounds.size.width, bounds.size.height)/2.0);    UIBezierPath  *path = [[UIBezierPath alloc] init ];    [path  addArcWithCenter:center  radius:radius  startAngle:0.0 endAngle:M_PI *2 clockwise:YES];    path.lineWidth =2;    [[UIColor redColor] setStroke];    [[UIColor lightGrayColor] setFill];    [path fill];    [path stroke];}    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {    //首先调用父类的方法确定点击的区域确实在按钮的区域中    BOOL res = [super pointInside:point withEvent:event];    if (res) {        //绘制一个圆形path//        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.bounds];        CGRect bounds = self.bounds;        CGPoint center;        center.x = bounds.origin.x +bounds.size.width/2.0;        center.y = bounds.origin.y +bounds.size.height/2.0;        float radius = (MIN(bounds.size.width, bounds.size.height)/2.0);        UIBezierPath  *path = [[UIBezierPath alloc] init ];        [path  addArcWithCenter:center  radius:radius  startAngle:0.0 endAngle:M_PI *2 clockwise:YES];        path.lineWidth = 1;        if ([path containsPoint:point]) {            //如果在path区域内,返回YES            return YES;        }        return NO;    }    return NO;}@end
0 0