iOS 画不规则的按钮

在绘制不规则的图形的时候我们经常将UIBezierPathCAShapeLayer联合起来一起使用,以期望达到我们想要的效果。下图是项目中我要实现的效果。
7C579CB9-342B-42D5-BB70-CA21DB0324D2.png

左边是学生登录的按钮,右边是老师登录的按钮,来回的点击使其切换不同身份的登录,下面附上老师按钮的代码

_teacherBtnPath = [UIBezierPath bezierPath];
    _teacherBtnPath.lineWidth = 2;
    UIColor *color = [UIColor yellowColor];
    [color set];
    
    [_teacherBtnPath moveToPoint:CGPointMake(0, 0)];
    [_teacherBtnPath addLineToPoint:CGPointMake(100, 0)];
    [_teacherBtnPath addLineToPoint:CGPointMake(100,60)];
    [_teacherBtnPath closePath];
    [_teacherBtnPath stroke];
    [_teacherBtnPath fill];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = CGRectMake(0, 0, 120,60);
    maskLayer.path = _teacherBtnPath.CGPath;
    self.teacherBtn.layer.mask = maskLayer;
    self.teacherBtn.layer.masksToBounds = NO;

学生按钮的代码基本类似,只是UIBezierPath部分的代码发生了变化

[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(SCREEN_WIDTH - 100, 0)];
[path addLineToPoint:CGPointMake(SCREEN_WIDTH, 60)];
[path addLineToPoint:CGPointMake(0, 60)];

这样画出如上的效果是没有问题的,但是在点击如下图的位置的时候应该是学生登录的,实际上却是老师登录,这说明虽然切割按钮成功了,但是按钮的有效点击范围不对。

7C579CB9-342B-42D5-BB70-CA21DB0324D2.png

后来发现是缺少了判断当前的点击或者触摸事件的点是否在当前的view中。

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{}的作用是判断当前的点击或者触摸事件的点是否在当前的view中。

若返回NO,则hitTest:withEvent:返回nil;
若返回YES,则向当前视图的所有子视图(subviews)发送hitTest:withEvent:消息,所有子视图的遍历顺序是从top到bottom,即从subviews数组的末尾向前遍历,直到有子视图返回非空对象或者全部子视图遍历完毕,当返回YES的时候进行你需要的操作。

.h
#import 

@interface PointInsideButton : UIButton

@property (strong ,nonatomic) UIBezierPath *teacherBtnPath;
@property (copy, nonatomic) void (^clcikChangeTitleBlock)();

@end
.m
#import "PointInsideButton.h"

@interface PointInsideButton ()


@end
@implementation PointInsideButton


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

    BOOL res = [super pointInside:point withEvent:event];
    if (res) {
        
        if ([_teacherBtnPath containsPoint:point]) {
            if (self.clcikChangeTitleBlock) {
                self.clcikChangeTitleBlock();
            }
            return YES;
        }
    }
    return  NO;
    /*最后在用_teacherBtn调用一下判断当前点击的point是否在其范围内就OK了。
_teacherBtn.teacherBtnPath = _teacherBtnPath; */
}  

你可能感兴趣的:(iOS 画不规则的按钮)