【问题标题】:Swift - Create circle and add to arraySwift - 创建圆圈并添加到数组
【发布时间】:2014-08-11 20:38:40
【问题描述】:

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

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

【问题讨论】:

    标签: arrays swift geometry


    【解决方案1】:

    画圆的方法有很多种,下面是我一直在hack的一个sn-p:

    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 特定功能)以添加一个带中心的初始化程序,但这对您的问题并不重要。

    【讨论】:

    • 不知道为什么我得到了反对票,在 OP 添加他的 coide sn-p 之前发布
    【解决方案2】:

    您的代码不是“创建”一个圆作为对象,而是尝试在图形上下文中绘制一个。您需要做的是创建一个贝塞尔路径对象,绘制到该对象并将路径保存在您的数组中。比如:

        var circleArray = [CGMutablePathRef]()
        // ...
        let path: CGMutablePathRef = CGPathCreateMutable()
        CGPathAddArc(path, nil, touchLocation.x, touchLocation.y, radius, 0, M_PI * 2, true)
        circleArray  += [path]
    

    然后您需要在绘图例程中描边路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多