drawRect-饼状环形图

一直都觉得会画图的人都很高大上,所以为了显得高大上点,我也搞了下绘图。

饼状图
1、首先要在- (void)drawRect:(CGRect)rect {
}
方法中获取当前的上下文
CGContextRef context = UIGraphicsGetCurrentContext();

2、然后我们就开始绘制了,我们需要先把这个环形的的底部背景图给绘制出来。另外有一点我很无奈就是这个顺时针和逆时针的问题clockwise:文档上说的YES是顺时针,但是为毛我用的时候设置为NO才达到我的效果呢

/**
 绘制环形背景图

 @param redius 半径
 @param point 中心点
 @param color 背景颜色
 @param context 上下文
 */
- (void)drawPieChartBackGroundWithRedius:(CGFloat)redius withCenter:(CGPoint)point withWidth:(CGFloat)width withColor:(UIColor *)color andContextRef:(CGContextRef)context
{
//起点
    CGFloat startAngle = 0;
//终点   
 CGFloat  endAngle = M_PI * 2;

    CGContextSetLineWidth(context, width);//线宽
    [color setStroke]; // 颜色

    //路径
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:point radius:redius startAngle:startAngle endAngle:endAngle clockwise:NO];
//添加路径
    CGContextAddPath(context, path.CGPath);
    //绘制内容
    CGContextDrawPath(context, kCGPathStroke);
}

3、背景图绘制完成之后就需要我们绘制上面的图层了

- (void)drawPieChartWithRedius:(CGFloat)redius withCenter:(CGPoint)point withWidth:(CGFloat)width withColor:(UIColor *)color andContextRef:(CGContextRef)context
{
    // 圆环轨迹
    CGFloat startAngle = -M_PI_2;
    CGFloat endAngle = startAngle + 2 * M_PI * self.progress;
    CGContextSetLineWidth(context, width);
    [color setStroke];
    CGContextAddArc(context, point.x, point.y, redius, startAngle, endAngle, NO);
    CGContextDrawPath(context, kCGPathStroke);
}

4、最后就是我们绘制环形图上的文字了

/**
 画文字

 @param string 文字内容
 @param point 中心点
 @param font 字号
 @param color 颜色
 @param context 上下文
 */
- (void)drawTextWithString:(NSString *)string withCenterPoint:(CGPoint)point withFont:(CGFloat)font withColor:(UIColor *)color andContext:(CGContextRef)context
{
//设置文字的样式
    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    textStyle.lineBreakMode = NSLineBreakByCharWrapping;
    textStyle.alignment = NSTextAlignmentCenter;

    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:font],NSParagraphStyleAttributeName:textStyle};
    CGSize textSize = [string sizeWithAttributes:attributes];
    CGRect textRect = CGRectMake(point.x-textSize.width/2, point.y - textSize.height/2, textSize.width, textSize.height);
    [string drawInRect:textRect withAttributes:attributes];
    [color setFill];
    CGContextDrawPath(context, kCGPathFill);
}

地址:demo
间书:地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值