iOS UILabel重绘

效果图

在这里插入图片描述

iOS中圆在顺时针方向的时候圆的0点位置

在这里插入图片描述

创建一个Label继承自UILabel,并重写- (void)drawRect:(CGRect)rect;

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 宽度
    CGFloat w = rect.size.width;
    // 高度
    CGFloat h = rect.size.height;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    // 起点(0,0)
    [path moveToPoint:CGPointMake(0, 0)];
    // 从(0, 0)画一条线到(w - h, 0)
    [path addLineToPoint:CGPointMake(w - h, 0)];
    // 以(w - h, h)为圆中心,h为半径, 顺时针方向画一段1/4圆弧, clockwise:顺时针
    [path addArcWithCenter:CGPointMake(w - h, h) radius:h startAngle:-M_PI_2 endAngle:0 clockwise:YES];
    //  从(w, h)画一条直线到(h, h)
    [path addLineToPoint:CGPointMake(h, h)];
    // 以(h, 0)为圆中心,h为半径, 顺时针方向画一段1/4圆弧, clockwise:顺时针
    [path addArcWithCenter:CGPointMake(h, 0) radius:h startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
    // 封闭绘制路径
    [path closePath];
    // 设置填充颜色为红色
    [UIColor.redColor setFill];
    // 将绘制路径添加到上下文中
    CGContextAddPath(context, path.CGPath);
    CGContextFillPath(context);
    
    // 千万注意一定要在最后调用父类方法,不然就无法显示文字,也无法调整对其的相关属性
    [super drawRect:rect];
}

猜你喜欢

转载自blog.csdn.net/renjie_Yan/article/details/89512708