Xcode - Draw Circle Around Centre

2019-04-11 09:45发布

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);

2条回答
我只想做你的唯一
2楼-- · 2019-04-11 10:36

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

查看更多
聊天终结者
3楼-- · 2019-04-11 10:42

You just need to translate to the point first

cgContextRef.translateBy(x:circlePoint.x, y:circlePoint.y)

Note this is Swift 3, it may be different in other languages, just search "translate cgcontext"

查看更多
登录 后发表回答