1
votes

I want to draw a circle by using just center (x,y) and radius r.

I drew some circles by using CGRect. It works fine when I draw independent circle. But I am trying to draw circles on circumference of a circle.

In this approach Problem is: The main circle is not moving exactly center of the outside circles, as outside circles are made using CGRect/frame.

So Please help me if we could just draw a circle using center and radius.

3

3 Answers

8
votes

X,Y and radius are your variables.

CGRect r;

r.origin.y = Y-radius;
r.origin.x = X-radius;
r.size.width = 2*radius;
r.size.height 2*radius;

then draw the circle in this CGRect

0
votes

Francesco's answer works. The only thing I'd add is to clarify what Y and X are (centre Y and centre X). Here is what I ended up with including the drawing, and I also fill the circle with same colour as the outer line.

CGFloat radius = self.bounds.size.height/4.0;
CGFloat centerX = self.bounds.size.width/2;
CGFloat centerY = self.bounds.size.height/2;

CGRect r;
r.origin.y = centerY-radius;
r.origin.x = centerX-radius;
r.size.width = 2*radius;
r.size.height = 2*radius;

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context,
                                     [UIColor greenColor].CGColor);
CGContextAddEllipseInRect(context, r);
CGContextStrokePath(context);

CGContextSetFillColorWithColor(context,
                                   [UIColor greenColor].CGColor);
CGContextFillEllipseInRect(context, r);
0
votes

You can draw a circle in the draw(_ rect: CGRect) method with using a bezier path like below.

import UIKit
import CoreGraphics

class CircleView: UIView {
    var radius: Double = 200.0
    var lineWidth: CGFloat = 5.0
    var centre = CGPoint.zero
    override func draw(_ rect: CGRect) {
        var arrRadians = [Double]()
        let pieVal = Double.pi * 2.0
        let incrVal = pieVal / 100
        arrRadians = stride(from: 0, to: 100, by: incrVal).map{$0}
        for rad in arrRadians {
            let sinRad = (sin(rad) * radius) + Double((rect.size.width / 2))
            let cosRad = (cos(rad) * radius) + Double((rect.size.height / 2))
            let point = CGPoint(x: sinRad, y: cosRad)
            let path = UIBezierPath()
            path.move(to: centre == CGPoint.zero ? point : centre)
            path.addLine(to: point)
            centre = point
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = path.cgPath
            shapeLayer.strokeColor = UIColor.red.cgColor
            shapeLayer.lineWidth = lineWidth
            self.layer.addSublayer(shapeLayer)
        }
    }
}

Then use setNeedsDisplay() method in for changing the radius of the circle.

viewCircle.radius = 100
viewCircle.setNeedsDisplay()

Result:

enter image description here