IOS学习 绘图 UIBezierPath 绘饼状图

本文介绍了一个使用Objective-C编写的自定义UIView子类,该视图用于绘制饼状图。文章详细展示了如何通过获取图形上下文对象、创建路径、设置圆心、半径等属性来实现饼状图的绘制,并通过for循环进行具体绘图操作。此外,还提供了一个点击视图触发重新绘制的方法,以改变颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import "CZView.h"

#define RECT_WIDTH rect.size.width

#define RECT_HEIGHT rect.size.height

@implementation CZView


- (void)drawRect:(CGRect)rect {

    CGFloat width = rect.size.width;

    CGFloat hight = rect.size.height;

    [self demo1:width withHeight:hight]; //传递两个参数

}


//饼状图

-(void)demo1:(CGFloat )width withHeight:(CGFloat)hight{

    NSArray *data = @[@30, @15, @5, @18, @2, @10, @12,@8];

    

    //1.获取图形上下文对象

    //    CGContextRef ctx = UIGraphicsGetCurrentContext();

    

    //2.创建路径

    //设置圆心

    CGPoint centerP = CGPointMake(width/2, hight/2);

    

    //设置半径

    CGFloat radius = MIN(width, hight)/2;

    

    //设置起始弧度和结束弧度

    

    CGFloat start = 0;

    

    CGFloat end = 0;

    

    //通过for循环绘图

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

    {

        

        end = ([data[i] floatValue]/100) * 2 * M_PI + start;

        

        UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:start endAngle:end clockwise:YES];

        

        //链接圆心

        [path addLineToPoint:centerP];

        

        //设置填充颜色

        [[self randomColor] set];

        [path fill];  //渲染

        //结束点的位置就是下一个弧的起点

        start = end;

    }    

    

    //3.把路径添加到上下文对象中

    //    CGContextAddPath(ctx, path.cgpath)

    

    //4.渲染

}


//点击view执行重绘

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    //执行重绘,颜色随机变

    [self setNeedsDisplay];

}


- (UIColor *) randomColor

{

    //随机红绿蓝

    CGFloat red = arc4random_uniform(256)/255.f//随机值

    CGFloat green = arc4random_uniform(256)/255.f;

    CGFloat blue = arc4random_uniform(256)/255.f;

    

    UIColor * color = [UIColor colorWithRed:red green:green blue:blue alpha:1.f];

    

    return color;

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值