您的位置:首页 > 其它

Quartz2D 之饼状图、柱状图、进度条

2015-12-31 23:45 260 查看
Quartz2D绘图的代码步骤
1.获得图形上下文
CGContextRef ctx=
UIGraphicsGetCurrentContext();

2.拼接路径(下面代码是搞一条线段)
CGContextMoveToPoint(ctx,10,
10);

CGContextAddLineToPoint(ctx,100,
100);

3.绘制路径
CGContextStrokePath(ctx);
//CGContextFillPath(ctx);

饼状图

- (void)drawRect:(CGRect)rect
{

NSArray * data = @[@30, @15, @5, @17, @3, @10, @20];

// 1.获取图形上下文

CGContextRef ctxRef = UIGraphicsGetCurrentContext();

// 起始角度
CGFloat startA = 0;

for (int i = 0; i < data.count; i ++) {

// 取出元素
int num = [data[i] intValue];

// 度数
CGFloat angle = num / 100.0 * M_PI * 2;

// 中心点
CGPoint center = CGPointMake(150, 150);
// 半径
CGFloat rad = 100;
// 终止角度
CGFloat endA = startA + angle;
// 创建<span style="font-family: Arial, Helvetica, sans-serif;">UIBezierPath对象</span>

UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:center radius:rad startAngle:startA endAngle:endA clockwise:YES];

[path addLineToPoint:center];
// 颜色
[[UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0] setFill];

CGContextAddPath(ctxRef, path.CGPath);

// 渲染
CGContextDrawPath(ctxRef, kCGPathFill);

startA = endA;

}

}



柱状图

- (void)drawRect:(CGRect)rect
{

NSArray * data = @[@300, @150.65, @55.3, @507.7, @95.8, @700, @650.65];
// 获取图形上下文

CGContextRef ctxRef = UIGraphicsGetCurrentContext();

for (int i = 0; i < data.count; i ++) {

float num = [data[i] floatValue];

// 高度
float height = num / 1000.0 * rect.size.height;

float width = rect.size.width / (data.count * 2 - 1);

// x
CGFloat x = width * 2 * i;
// y
CGFloat y = rect.size.height - height;

UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, width,height)];

// 颜色
[[UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0] setFill];

CGContextAddPath(ctxRef, path.CGPath);

// 渲染
CGContextDrawPath(ctxRef, kCGPathFill);
}

}



进度条

- (void)drawRect:(CGRect)rect
{

// 获取图形上下文

CGContextRef ctxRef = UIGraphicsGetCurrentContext();

CGPoint center = CGPointMake(150, 150);

CGFloat r1 = 100;

CGFloat r2 = 70;

CGFloat startA = - M_PI_2;

CGFloat endA = self.angle * M_PI * 2 - M_PI_2;

UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:center radius:r1 startAngle:startA endAngle:endA clockwise:YES];

UIBezierPath * path2 = [UIBezierPath bezierPathWithArcCenter:center radius:r2 startAngle:endA endAngle:startA clockwise:NO];

[path addLineToPoint:center];

[path2 addLineToPoint:center];
[[UIColor greenColor] setFill];

CGContextAddPath(ctxRef, path.CGPath);
CGContextAddPath(ctxRef, path2.CGPath);

// 渲染
CGContextDrawPath(ctxRef, kCGPathFill);

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: