画出一个圆圈的一部分

Wim*_*tra 25 iphone cocoa-touch objective-c

对于iPhone应用程序,我想绘制一个圆圈,仅用于填充x百分比.

像这样的东西:

替代文字

我没有问题计算半径,度数或弧度,这是没有问题的.绘制圆圈也已完成.但是如何让iPhone SDK绘制已填充的部分.

我可以画一个大小的矩形,但不是圆的一部分.

我只想在一个正常的背景下绘制它.

希望有人能在这里给我任何指示.

Dav*_*ist 46

很多人已经向您展示了如何在Core Graphics中完成这项工作,但它也可以通过Core Animation完成,它可以很容易地为饼形的百分比设置动画.

以下代码将创建环和部分填充的图层(即使您说您已经可以绘制环),因为它很好地使用相同的方法绘制环和饼形状.

如果为pieShape图层的strokeStartstrokeEnd属性设置动画,则将具有动画百分比.与所有Core Animation代码一样,您需要将QuartzCore.framework添加到您的项目中并包含<QuartzCore/QuartzCore.h>在您的代码中.

// Create a white ring that fills the entire frame and is 2 points wide.
// Its frame is inset 1 point to fit for the 2 point stroke width
CGFloat radius = MIN(self.frame.size.width,self.frame.size.height)/2;
CGFloat inset  = 1;
CAShapeLayer *ring = [CAShapeLayer layer];
ring.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset) 
                                       cornerRadius:radius-inset].CGPath;

ring.fillColor   = [UIColor clearColor].CGColor;
ring.strokeColor = [UIColor whiteColor].CGColor;
ring.lineWidth   = 2;

// Create a white pie-chart-like shape inside the white ring (above).
// The outside of the shape should be inside the ring, therefore the
// frame needs to be inset radius/2 (for its outside to be on 
// the outside of the ring) + 2 (to be 2 points in).
CAShapeLayer *pieShape = [CAShapeLayer layer];
inset = radius/2 + 2; // The inset is updated here
pieShape.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
                                        cornerRadius:radius-inset].CGPath;
pieShape.fillColor   = [UIColor clearColor].CGColor;
pieShape.strokeColor = [UIColor whiteColor].CGColor;
pieShape.lineWidth   = (radius-inset)*2;   

// Add sublayers
// NOTE: the following code is used in a UIView subclass (thus self is a view)
// If you instead chose to use this code in a view controller you should instead
// use self.view.layer to access the view of your view controller.
[self.layer addSublayer:ring];
[self.layer addSublayer:pieShape];
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案. (4认同)

Dav*_* M. 20

使用CGContext弧功能:

CGContextAddArc(context,
                centerX,
                centerY,
                radius,
                startAngleRadians,
                endAngleRadians,
                clockwise ? 1 : 0);     
Run Code Online (Sandbox Code Playgroud)

请参阅文档CGContextAddArc().

  • 这很容易修复.只需在之前的行中添加`CGContextMoveToPoint(context,centerX,centerY);`. (3认同)

mha*_*per 8

试试这个:

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
Run Code Online (Sandbox Code Playgroud)


Sam*_*fes 6

我实现了一个类似于你正在做的饼图进度视图.它是开源的.希望源代码会有所帮助.

SSPieProgressView.h源码

SSPieProgressView.m源码