我一直试图弄清楚如何在这个项目中使用UIBezierPath,但我不知道如何实现这种绘图。我可以绘制一个圆弧,直线和直线,但我觉得这个很丢失。感谢帮助
答案 0 :(得分:11)
要在名为UIBezierPath
的{{1}}上绘制正弦波,请使用path
绘制多个线段。诀窍是将角度(path.addLine(to:)
转换为0
)转换为点的360
坐标,将x
转换为点的sin(x)
坐标。
以下是一个例子:
y
此处它正在Playground中运行:
@Rob更新了此代码,除了添加class SineView: UIView{
let graphWidth: CGFloat = 0.8 // Graph is 80% of the width of the view
let amplitude: CGFloat = 0.3 // Amplitude of sine wave is 30% of view height
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let origin = CGPoint(x: width * (1 - graphWidth) / 2, y: height * 0.50)
let path = UIBezierPath()
path.move(to: origin)
for angle in stride(from: 5.0, through: 360.0, by: 5.0) {
let x = origin.x + CGFloat(angle/360.0) * width * graphWidth
let y = origin.y - CGFloat(sin(angle/180.0 * Double.pi)) * height * amplitude
path.addLine(to: CGPoint(x: x, y: y))
}
UIColor.black.setStroke()
path.stroke()
}
}
let sineView = SineView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
sineView.backgroundColor = .white
属性外,还使@IBDesignable
具有@IBInspectable
属性。看看他的回答here。
答案 1 :(得分:0)
这允许您将正弦波放置在矩形内:
func generateWave(cycles: Int, inRect: CGRect, startAngleInDegrees: CGFloat = 0) -> UIBezierPath {
let dx = inRect.size.width
let amplitude = inRect.size.height
let scaleXToDegrees = 1 / (inRect.size.width / 360.0 / CGFloat(cycles))
let path = UIBezierPath()
for x in stride(from: 0, to: dx + 5, by: 5) {
let y = sin(D2R(startAngleInDegrees + x * scaleXToDegrees)) * amplitude / 2
let p = CGPoint(x: x + inRect.origin.x, y: y + inRect.origin.y)
if x == 0 {
path.move(to: p)
} else {
path.addLine(to: p)
}
}
return path
}
动画:
override func update(_ currentTime: TimeInterval) {
shape?.removeFromParent()
let path = generateWave(cycles: 7, inRect: targetRect, startAngleInDegrees: currentStartAngle)
shape = SKShapeNode(path: path.cgPath)
shape!.strokeColor = .red
shape!.lineWidth = 1
self.addChild(shape!)
currentStartAngle += 5
}