dgee4 dgee4 - 1 month ago 8
iOS Question

Xcode - Draw Circle Around Centre

I was wondering how to draw a circle around a point taken from a control's positioning.

This is not working as hoped

CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(contextRef, 2.0);
CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
CGRect circlePoint = (CGRectMake(self.frame.size.width / 2, self.frame.size.height / 2, 10.0, 10.0));

CGContextFillEllipseInRect(contextRef, circlePoint);

Answer Source

I think its pretty easy to draw a circle using UIBezierPath. All you need to do is subclass UIView and create UIBezierPath. I have created a example using UIBezierPath :

Create a subclass of UIView called CirecleView. Add following code :

#import "CircleView.h"

@implementation CircleView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGFloat rectX = self.frame.size.width / 2;
    CGFloat rectY = self.frame.size.height / 2;
    CGFloat width = 100;
    CGFloat height = 100;
    CGFloat centerX = rectX - width/2;
    CGFloat centerY = rectY - height/2;


    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(centerX, centerY, width, height)];

    [[UIColor blackColor] set];
    [bezierPath stroke];
}

@end

Change your controller's view class to CircleView. Please see below picture.

enter image description here

Thats it. Run your code to present your controller's view. Following is the output :

enter image description here

You can down code example from here