Draw part of a circle

后端 未结 8 836
北海茫月
北海茫月 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:41

    Try this:

    CGContextMoveToPoint(the center point)
    CGContextAddLineToPoint(the starting point of the fill path on the circumference)
    CGContextAddArcToPoint(the ending point of the fill path on the circumference)
    CGContextAddLineToPoint(the center point)
    CGContextFillPath
    
    0 讨论(0)
  • 2020-11-27 04:46

    Below is a full method I am using that does this with Core Graphics, adapting and expanding on mharper's comment above.

    This code is for OSX Cocoa, but could easily be changed to iOS, by modifying how you get the context.

    - (void)drawPieShapedCircleWithRadius:(CGFloat)radius
                          strokeColor:(CGColorRef)strokeColor
                            fillColor:(CGColorRef)fillColor
                            lineWidth:(CGFloat)lineWidth
                       currentDegrees:(float)currentDegrees
                         startDegrees:(float)startDegrees {
        // get the context
        CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
    
        // Set the color of the circle stroke and fill
        CGContextSetStrokeColorWithColor(context, strokeColor);
        CGContextSetFillColorWithColor(context, fillColor);
    
        // Set the line width of the circle
        CGContextSetLineWidth(context, 1);
    
        // Calculate the middle of the circle
        CGPoint circleCenter = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
    
        // Move the bezier to the center of the circle
        CGContextMoveToPoint(context, circleCenter.x, circleCenter.y);  // move to the center point
    
        // Draw the arc from the start point (hardcoded as the bottom of the circle) to the center
        CGContextAddLineToPoint(context, circleCenter.x, circleCenter.y + radius);
    
        // Draw the arc around the circle from the start degrees point to the current degrees point
        CGContextAddArc(context, circleCenter.x , circleCenter.y, radius, [self radians:startDegrees], [self radians:startDegrees + currentDegrees], 0);
    
        // Draw the line back into the center of the circle
        CGContextAddLineToPoint(context, circleCenter.x, circleCenter.y);
    
        // Fill the circle
        CGContextFillPath(context);
    
        // Draw the line around the circle
        CGContextStrokePath(context);
    }
    
    0 讨论(0)
提交回复
热议问题