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];
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章