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
csdn:地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • --绘图与滤镜全面解析 概述 在iOS中可以很容易的开发出绚丽的界面效果,一方面得益于成功系统的设计,另一方面得益...
    韩七夏阅读 2,791评论 2 10
  • #define kBlackColor [UIColor blackColor] //.h //划线 + (voi...
    CHADHEA阅读 816评论 0 1
  • 原文出处 http://blog.csdn.net/u014286994/article/details/5133...
    Poison_19ce阅读 1,490评论 0 2
  • 装沙子 睡觉 晚上拿参赛包去爷爷奶奶家 烦 自己不说清楚 谁知道你想说什么 你发泄的方式说无理取闹 我也需要自己发...
    角落蜷缩阅读 183评论 0 0
  • 某一日,心血来潮,就编了一个小故事,逗自己乐: 在那片美丽的森林里,乌龟小姐和兔子先生三次赛跑以后终于相爱了,兔子...
    一树繁枝阅读 331评论 0 1