Xcode - 绘制围绕中心的圆形

3

我想知道如何在从控件定位中获取的点周围画一个圆。

这种方法并不能如愿以偿。

    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
它为什么不工作?它没有画圆吗? - Rafał Sroka
缺少一根笔画是你的问题吗? - David Rönnqvist
我遇到的问题是圆圈没有围绕给定点居中。 - dgee4
2个回答

4

我认为使用UIBezierPath很容易画出一个圆形。你只需要创建一个UIBezierPath的子类UIView,然后创建UIBezierPath即可。我已经用UIBezierPath创建了一个例子:

创建一个名为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。请参见下面的图片。 enter image description here 就这样了。运行您的代码以呈现您的控制器的视图。以下是输出结果: enter image description here 您可以从此处下载代码示例。

我遇到的问题是圆没有以给定点为中心。 - dgee4
我已经编辑了我的代码以使圆心居中。请根据您的需求提供适当的宽度和高度。 - Naga Mallesh Maddali
1
谢谢,我已经成功找到了相同的解决方案 :-) 非常感谢! - dgee4

1

你只需要先把话说到点子上

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

请注意,这是Swift 3的内容,其他语言可能会有所不同,只需搜索“translate cgcontext”即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接