Draw part of a circle

后端 未结 8 930
北海茫月
北海茫月 2020-11-27 04:03

For an iPhone application I want to draw a circle, that is only for an x percentage filled.

Something like this:

8条回答
  •  情歌与酒
    2020-11-27 04:25

    Try this code in a UIView, Example "MyChartClass"...

    - (void)drawRect:(CGRect)rect {
        int c=(int)[itemArray count];
    
        CGFloat angleArray[c];
        CGFloat offset;
        int sum=0;
    
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSetAllowsAntialiasing(context, false);
        CGContextSetShouldAntialias(context, false);
    
        for(int i=0;i<[itemArray count];i++) {
            sum+=[[itemArray objectAtIndex:i] intValue];
        }
    
        for(int i=0;i<[itemArray count];i++) {
            angleArray[i]=(float)(([[itemArray objectAtIndex:i] intValue])/(float)sum)*(2*3.14); 
            CGContextMoveToPoint(context, radius, radius);
            if(i==0)
                CGContextAddArc(context, radius, radius, radius, 0,angleArray[i], 0);
            else
                CGContextAddArc(context, radius, radius, radius,offset,offset+angleArray[i], 0);
            offset+=angleArray[i];
    
            CGContextSetFillColorWithColor(context, ((UIColor *)[myColorArray objectAtIndex:i]).CGColor);
            CGContextClosePath(context); 
            CGContextFillPath(context);
    
        }   
    }
    

    Implementation in your UIViewController

    MyChartClass *myChartClass=[[MyChartClass alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    myChartClass.backgroundColor = [UIColor clearColor];
    myChartClass.itemArray=[[NSArray alloc]initWithObjects:@"75",@"25", nil];
    myChartClass.myColorArray=[[NSArray alloc]initWithObjects:[UIColor blackColor],[UIColor whiteColor], nil];
    myChartClass.radius=100;
    [self.view addSubview:myChartClass];
    

    Regards.

提交回复
热议问题