美文网首页iOS进阶+实战
iOS多边形按键类

iOS多边形按键类

作者: Realank | 来源:发表于2016-02-16 15:20 被阅读427次

头文件:

//
//  RLCShapeButton.h
//  duobianxing
//
//  Created by Realank on 16/2/16.
//  Copyright © 2016年 iMooc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RLCShapeButton : UIButton

- (instancetype)initWithPath:(UIBezierPath *)path andOrigin:(CGPoint)point;

@end

实现文件:

//
//  RLCShapeButton.m
//  duobianxing
//
//  Created by Realank on 16/2/16.
//  Copyright © 2016年 iMooc. All rights reserved.
//

#import "RLCShapeButton.h"

@interface RLCShapeButton ()

@property(nonatomic, strong) UIBezierPath *path;

@end
@implementation RLCShapeButton

- (instancetype)initWithPath:(UIBezierPath *)path andOrigin:(CGPoint)point{
    if (self = [super initWithFrame:CGRectMake(point.x, point.y, path.bounds.size.width, path.bounds.size.height)]) {
        _path = path;
        CAShapeLayer *shapLayer = [CAShapeLayer layer];
        shapLayer.path = self.path.CGPath;
        shapLayer.strokeColor = [UIColor redColor].CGColor;
        shapLayer.lineWidth = 5;
        shapLayer.fillColor = [UIColor clearColor].CGColor;
//        self.layer.mask = shapLayer;
        [self.layer addSublayer:shapLayer];
    }
    return self;
}

//绘制按钮时添加path遮罩
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

}

//覆盖方法,点击时判断点是否在path内,YES则响应,NO则不响应
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    BOOL res = [super pointInside:point withEvent:event];
    if (res)
    {
        if ([self.path containsPoint:point])
        {
            return YES;
        }
        return NO;
    }
    return NO;
}

@end

VC中调用:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBezierPath* path = [[UIBezierPath alloc]init];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(50, 50)];
    [path addLineToPoint:CGPointMake(100, 50)];
    [path addLineToPoint:CGPointMake(100,100)];
    [path addLineToPoint:CGPointMake(0, 100)];
    [path closePath];

    RLCShapeButton *button = [[RLCShapeButton alloc]initWithPath:path andOrigin:CGPointMake(100, 100)];
    [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}

- (void)click {
    NSLog(@"click");
}

相关文章

网友评论

    本文标题:iOS多边形按键类

    本文链接:https://www.haomeiwen.com/subject/phgpkttx.html