CGContextAddArc绘制不同大小的多个圆圈

时间:2016-08-09 04:43:06

标签: ios objective-c swift

我有这些尺寸,我想绘制一个圆圈(宽度和高度明显相同)

205.0
218.0
245.0
257.0
310.0
510.0

当我在205.5画出我的圆圈时,它是一个完美的圆圈。但是当我从218开始时,圆圈会被切断一点,每当我试图做一个更大的圆圈时它就越来越多。我的问题是,无论大小如何,我如何创建一个完美的圆圈?

这是我的代码:

func drawCircle()
{
    // Get the Graphics Context
    let context = UIGraphicsGetCurrentContext();

    // Set the circle outerline-width
    CGContextSetLineWidth(context, 5.0);

    // Set the circle outerline-colour
    UIColor.redColor().set()

    // Create Circle
    CGContextAddArc(context, (round(frame.size.width))/2, round(frame.size.height)/2, (round(frame.size.width) - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1)

    // Draw
    CGContextStrokePath(context);
}

frame.size.widthframe.size.height是205,218等的数字。我会接受一个Objective-C答案。

2 个答案:

答案 0 :(得分:3)

如果您想画一个圆圈,use CGContext.addEllipse(in:) a.k.a. CGContextAddEllipseInRect而不是CGContextAddArc

// swift 3:
let context = UIGraphicsGetCurrentContext()!
context.setLineWidth(5.0)
UIColor.red.set()

context.addEllipse(in: frame) // <--

context.strokePath()


// swift 2:
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 5.0)
UIColor.redColor().set()

CGContextAddEllipseInRect(context, frame)  // <-- 

CGContextStrokePath(context)

答案 1 :(得分:0)

您绘制的视图需要足够大才能绘制所有这些圆圈(所以510+ x 510+)。你可以设置clipsToBounds = false来绕过它,但这通常不是一个好主意。

UIBezierPath有一个简单的圆形路径初始化器。您可以使用它来绘制圆圈并指定半径。

// Use the center of the bounds of the view so we draw circles centered in our view.
// If you use self.center, this will be in the parent view's coordinate system and your circles could be off center.
CGPoint centerOfBounds = CGPointMake((self.bounds.origin.x + self.bounds.size.width) / 2, (self.bounds.origin.y + self.bounds.size.height) / 2);

// The startAngle, endAngle and clockwise don't matter much here since we are drawing a full circle.
// The only requirement is the start and end angle MUST be 2*PI apart.
UIBezierPath *two05 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:205.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];
UIBezierPath *two18 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:218.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];
UIBezierPath *two45 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:245.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];
UIBezierPath *two57 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:257.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];
UIBezierPath *three10 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:310.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];
UIBezierPath *five10 = [UIBezierPath bezierPathWithArcCenter:centerOfBounds radius:510.0/2, startAngle:0 endAngle:2*M_PI clockwise:false];

// Set the color, line widths on the path, and call stroke on each bezier path to draw the circles
[[UIColor blueColor] setStroke];
two05.lineWidth = 1;
[two05 stroke];
// Reapeat for other paths...