iOS drawRect绘制圆形/圆环/饼图

24 篇文章 0 订阅

效果如下图的圆,中间的内容可自己添加;隐藏中间白色的圆即是一个饼图
在这里插入图片描述

调用方法:

GradeView *gradeView = [[GradeView alloc] init];
gradeView.grade = @"0.8";
需要更新需要调用:
gradeView.grade = @"0.9";
[gradeView setNeedsDisplay];

GradeView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface GradeView : UIView

@property (nonatomic, strong) NSString *grade;

@end

NS_ASSUME_NONNULL_END

GradeView.m

#import "GradeView.h"

@implementation GradeView

- (void)setGrade:(NSString *)grade {
    _grade = grade;
}

//计算度转弧度
static inline float radians(double degrees) {
    return degrees * M_PI / 180;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGFloat borderWidth = 20;
    CGFloat radius = self.bounds.size.height / 2;
    CGFloat grade = self.grade ? self.grade.floatValue : 1;
    grade = grade > 0 ? grade : 0;
    UIColor *bgColor = HEXCOLOR(@"ffffff");
    UIColor *tintColor = Color_Global_Light;
    UIColor *onTintColor = Color_Global;
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);

    //填充当区域内的颜色与父视图相同
    [bgColor set];
    CGContextFillRect(context, rect);
    CGContextFillPath(context);

    //绘制两个扇形
    float angle_start = radians(0.0);
    float angle_end = radians(360 * grade);
    CGContextMoveToPoint(context, center.x, center.y);
    CGContextSetFillColor(context, CGColorGetComponents(onTintColor.CGColor));
    CGContextAddArc(context, center.x, center.y, radius, angle_start, angle_end, 0);
    CGContextFillPath(context);

    angle_start = angle_end;
    angle_end = radians(360.0);
    CGContextMoveToPoint(context, center.x, center.y);
    CGContextSetFillColor(context, CGColorGetComponents(tintColor.CGColor));
    CGContextAddArc(context, center.x, center.y, radius, angle_start, angle_end, 0);
    CGContextFillPath(context);

    //绘制圆颜色与父视图相同
    CGFloat w = (self.bounds.size.width)/ 2 - borderWidth;
    CGContextAddEllipseInRect(context, CGRectMake(center.x - w, center.y - w, w * 2, w * 2));
    [bgColor set];
    CGContextFillPath(context);//实心的
    CGContextStrokePath(context);//空心的

    //调整方向
    self.layer.transform = CATransform3DMakeRotation(M_PI * -0.5, 0, 0, 1);
    self.layer.shadowRadius = radius;
    self.layer.masksToBounds = YES;
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值