iOS 图表绘制

作者: HJXu | 来源:发表于2016-08-23 12:03 被阅读136次

1,柱型图绘制

-(void)drawRect:(CGRect)rect
{
    //画xy轴
   CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor redColor]set];
    
    CGContextSetLineWidth(context, 2);
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, 200, 0);
    
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, 0, 200);
    CGContextStrokePath(context);
    
    
    //画中间的线条
    [[UIColor grayColor]set];
    CGContextSetLineWidth(context, 1);
    CGFloat startX = 0;
    CGFloat marginW = 20;
    CGFloat startY = 200;
    CGFloat endY = 0;
    
    
    for (int i = 0; i<10; i++) {
        startX += marginW;
        CGContextMoveToPoint(context, startX, startY);
        CGContextAddLineToPoint(context, startX, endY);
        CGContextStrokePath(context);
    }
 UIColor *acolor;
    CGFloat squareX = 1;
    CGFloat squareY = 0;
    CGFloat squareW = 0;
    CGFloat squareH = 20;
    
    for (int i = 0; i<5; i++) {
        squareY += 30;
        squareW = arc4random_uniform(200);
        acolor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1];
        CGContextSetLineWidth(context, 0.1); 
        CGContextSetFillColorWithColor(context, acolor.CGColor);
        CGContextAddRect(context, CGRectMake(squareX, squareY, squareW, squareH));
        CGContextDrawPath(context, kCGPathFillStroke);
    }
}

2,饼图

-(void)drawRect:(CGRect)rect
{
    NSArray *angleArr = @[@10,@20,@40,@30];
    CGFloat startA = 0;
    CGFloat endA = 0;
    CGFloat angle = 0;
    CGPoint center = CGPointMake(rect.size.width/2, rect.size.height/2);
    //绘制饼图
    for (NSNumber *num in angleArr) {
        startA = endA;
        angle = [num integerValue]/100.0*M_PI*2;
        endA = startA + angle;
       UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:rect.size.width/2 startAngle:startA endAngle:endA clockwise:YES];
        [path addLineToPoint:center];
        [[self randomColor]set];
        [path fill];
    }
        
}

-(UIColor *)randomColor
{
    CGFloat r = arc4random_uniform(256)/255.0;
    CGFloat g = arc4random_uniform(256)/255.0;
    CGFloat b = arc4random_uniform(256)/255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

效果如下


947C72E5-353D-457B-99E8-52FB03452782.png

相关文章

网友评论

    本文标题:iOS 图表绘制

    本文链接:https://www.haomeiwen.com/subject/teagsttx.html