2017-08-26 89 views
0

我想使这个UIView的与UIBezierPath:使旭日斯威夫特与UIBezierPath

enter image description here

随着旋转它(虽然我可以让这对我自己,如果我知道如何绘制可选的能力,那旭日(这是我如何调用视图))

这里的答案是在目标C给出:https://stackoverflow.com/a/14991292/7715250

我试图把它与这个代码(复制粘贴在游乐场将工作)转换成斯威夫特:

import UIKit 

class SunBurst: UIView{ 
    override func draw(_ rect: CGRect) { 
     let radius: CGFloat = rect.size.width/2.0 
     UIColor.red.setFill() 
     UIColor.blue.setStroke() 
     let bezierPath = UIBezierPath() 
     let centerPoint = CGPoint(x: rect.origin.x + radius, y: rect.origin.y + radius) 
     var thisPoint = CGPoint(x: centerPoint.x + radius, y: centerPoint.y) 
     bezierPath.move(to: centerPoint) 
     var thisAngle: CGFloat = 0.0 
     let sliceDegrees: CGFloat = 360.0/20/2.0 
     let half: CGFloat = 180 
     let floatRadius = Float(radius) 

     for _ in 0..<20 { 
      let x = CGFloat((floatRadius * cosf(Float(.pi * thisAngle + sliceDegrees/half)))) + centerPoint.x 
      let y = CGFloat((floatRadius * sinf(Float(.pi * thisAngle + sliceDegrees/half)))) + centerPoint.y 
      thisPoint = CGPoint(x: x, y: y) 
      bezierPath.addLine(to: thisPoint) 
      thisAngle += sliceDegrees 
      let x2 = CGFloat((floatRadius * cosf(Float((.pi * thisAngle + sliceDegrees)/half)))) + centerPoint.x 
      let y2 = CGFloat((floatRadius * sinf(Float((.pi * thisAngle + sliceDegrees)/half)))) + centerPoint.y 
      thisPoint = CGPoint(x: x2, y: y2) 
      bezierPath.addLine(to: thisPoint) 
      bezierPath.addLine(to: centerPoint) 
      thisAngle += sliceDegrees 
     } 
     bezierPath.close() 
     bezierPath.lineWidth = 1 
     bezierPath.fill() 
     bezierPath.stroke() 
    } 
} 


let custom = SunBurst(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) 
custom.backgroundColor = .clear 

有了这样的结果:

enter image description here

我觉得我缺少的1行代码,因为它几乎看起来是正确的,但我缺少什么呢?我当然不是目标C的专家,我用https://objectivec2swift.com/#/home/converter/将链接上的代码与答案进行了转换。

除了它几乎看起来正确,它应该在横向模式下工作。当我降低高度并保持相同的宽度时,阳光照射会严重失败。它如何也可以在景观中工作?

感谢您的任何帮助,使正确的UIView。我认为这对游戏中的奖励视图来说看起来不错。

回答

5

问题是您的弧度计算程度缺乏正确的运算符优先级。

更换的每次使用(全4线):

.pi * thisAngle + sliceDegrees/half 

有:

.pi * (thisAngle + sliceDegrees)/half 

更好,添加一个degreesToRadians功能,所以你可以简单地传递thisAngle + sliceDegrees它和避免问题都在一起。