简体   繁体   English

Xcode - 围绕中心绘制圆圈

[英]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);

I think its pretty easy to draw a circle using UIBezierPath. 我认为使用UIBezierPath绘制圆圈非常容易。 All you need to do is subclass UIView and create UIBezierPath. 您需要做的就是创建UIView的子类并创建UIBezierPath。 I have created a example using UIBezierPath : 我使用UIBezierPath创建了一个示例:

Create a subclass of UIView called CirecleView. 创建一个名为CirecleView的UIView的子类。 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. 将控制器的视图类更改为CircleView。 Please see below picture. 请看下面的图片。

在此输入图像描述

Thats it. 而已。 Run your code to present your controller's view. 运行代码以显示控制器的视图。 Following is the output : 以下是输出:

在此输入图像描述

You can down code example from here 你可以从这里下来代码示例

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" 注意这是Swift 3,它可能与其他语言不同,只需搜索“translate cgcontext”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM