Xcode – 围绕中心绘制圆

我想知道如何围绕从控制的位置采取一个点。

这不是如所希望的那样工作

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

我觉得使用UIBezierPath绘制一个圆很容易。 所有你需要做的是UIView子类和创buildUIBezierPath。 我用UIBezierPath创build了一个例子:

创build一个名为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 

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

在这里输入图像说明

而已。 运行你的代码来呈现你的控制器的视图。 以下是输出:

在这里输入图像说明

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

你只需要首先翻译

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

注意这是Swift 3,它在其他语言中可能不同,只需search“translate cgcontext”