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
间书:地址

猜你喜欢

转载自blog.csdn.net/shutongit/article/details/54600457