CoreGraphics 自定义button

    //去的画布的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //画布大小
    CGContextAddRect(context, rect);
    //画布颜色
    [self.buttonColor set];
    //填充
    CGContextFillPath(context);

    UIBezierPath *roundeRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, 1, 1) cornerRadius:rect.size.height/2];
    //填充颜色
    [self.buttonColor setFill];
    //连线
    [roundeRectanglePath fill];
    //线颜色
    [[UIColor whiteColor] setStroke];
    //线宽度
    roundeRectanglePath.lineWidth = 1;

    [roundeRectanglePath stroke];
    
    //
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *att = @{NSParagraphStyleAttributeName:paragraphStyle,NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize size = [self.buttonTitle sizeWithAttributes:att];
    CGRect r = CGRectMake(rect.size.width/2 - size.width/2, rect.size.height/2 - size.height/2, size.width, size.height);
    //可以是image,这样就可以绘制图像
    [self.buttonTitle drawInRect:r withAttributes:att];

 点击效果

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    NSUInteger tapCount = touch.tapCount;
    switch (tapCount) {
        case 1:
            self.buttonClickBlock();
            break;
    
        default:
            break;
    }
}

最终效果

.h文件

原文地址:https://www.cnblogs.com/huoxingdeguoguo/p/5462676.html