我一直在寻找如何在 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/