Xcode - 在中心周围画圆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24954735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:16:40  来源:igfitidea点击:

Xcode - Draw Circle Around Centre

iosxcodedrawingcore-graphics

提问by dgee4

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

回答by Naga Mallesh Maddali

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 :

我认为使用 UIBezierPath 画一个圆很容易。您需要做的就是继承 UIView 并创建 UIBezierPath。我使用 UIBezierPath 创建了一个示例:

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

创建一个名为 CirecleView 的 UIView 子类。添加以下代码:

#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.

将控制器的视图类更改为 CircleView。请看下图。

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

您可以从这里下载代码示例

回答by Knight0fDragon

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”