arrays - Swift - 创建圆并添加到数组中

标签 arrays swift geometry

我一直在寻找如何在 Swift 中创建一个圆,但它看起来相当复杂。我想在运行时创建一个具有指定 x 和 y 以及宽度和高度的圆。然后我想将这个圆添加到一个数组中,我可以在其中创建更多圆并添加到其中。

我该怎么做?

编辑:这是我迄今为止尝试过的:

var center : CGPoint = touchLocation

var myContext : CGContextRef = UIGraphicsGetCurrentContext()

let color : [CGFloat] = [0, 0, 1, 0.5]
CGContextSetStrokeColor (myContext, color);
CGContextStrokeEllipseInRect (myContext, CGRectMake(touchLocation.x, touchLocation.y, 20, 20));

touchLocation 是用户手指的位置。在此行执行时会崩溃:

var myContext : CGContextRef = UIGraphicsGetCurrentContext()

错误显示“在解包可选值时意外发现 nil

此外,这不允许我将圆添加到数组中,因为我不知道它是什么变量类型。

最佳答案

画圆的方法有很多,这里是我一直在使用的一个片段:

func circleWithCenter(c:CGPoint, radius r:CGFloat,
    strokeColor sc: UIColor = UIColor.blackColor(),
    fillColor fc: UIColor = UIColor.clearColor()) -> CAShapeLayer {

        var circle = CAShapeLayer()
        circle.frame = CGRect(center:c, size:CGSize(width:2*r, height:2*r))
        circle.path = UIBezierPath(ovalInRect:circle.bounds).CGPath
        circle.fillColor = fc.CGColor
        circle.strokeColor = sc.CGColor
        circle.fillColor = fc == UIColor.clearColor() ? nil : fc.CGColor
        return circle
}

请注意,我扩展了 CGRect (使用 Swift 特定功能)来添加一个以中心为中心的初始值设定项,但这对您的问题并不重要。

关于arrays - Swift - 创建圆并添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25252005/

相关文章:

javascript - 使用属性名称在 javascript 中查找对象的索引

javascript - 使用 JQuery.inArray() 查找字符串

swift - 如何使用绑定(bind)关联 Swift 枚举数组?

ios - Swift 闭包数组, 'Int' 不是 '()' 的子类型

android - 如何使用多点触控画圆

algorithm - 给定点时如何确定哪个半径长

javascript - 为什么我在以下 javascript 代码中收到未定义的条目

javascript - 使用自定义排序函数在 JavaScript 中对多维数组进行排序

ios - 如何在 iOS Swift 中播放 Vimeo 视频?

python - HoughCircles圆检测使用opencv和python-