gpt4 book ai didi

swift - 两点之间的正弦波 UIBezierPath

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:14 26 4
gpt4 key购买 nike

如何在两点之间创建一条正弦波路径?

我能够从原点创建正弦波路径,但不确定如何转换方向以使正弦波在 objective-c GPoint 处结束。

我想使用 SKAction.followPath 沿路径设置 SKNode 的动画

最佳答案

考虑这一点的最简单方法是变换坐标系,旋转两点之间的角度,缩放两点之间的距离并平移第一点(假设正弦从 0,0 开始)。

OP 已指定他不只是想绘制曲线(在这种情况下,所有需要做的就是将变换应用于图形上下文),而是在 SpriteKit SKAction 中使用曲线.followPath 调用,因此必须将转换应用于路径中的坐标,而不是上下文。

这里有一个使用 CGPath 而不是 UIBezierPath 的解决方案,但它们是等价的,您可以通过 let uip = UIBezierPath(cgPath:路径)。 (我更喜欢 CoreGraphics,因为它们是跨平台的)。

Playground 代码...

class MyView: UIView {

override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }

context.setFillColor(UIColor.red.cgColor)
context.fill(self.bounds)

// Calculate the transform
let p1 = CGPoint(x: 100, y: 100)
let p2 = CGPoint(x: 400, y: 400)
let dx = p2.x - p1.x
let dy = p2.y - p1.y
let d = sqrt(dx * dx + dy * dy)
let a = atan2(dy, dx)
let cosa = cos(a) // Calculate only once...
let sina = sin(a) // Ditto

// Initialise our path
let path = CGMutablePath()
path.move(to: p1)

// Plot a parametric function with 100 points
let nPoints = 100
for t in 0 ... nPoints {
// Calculate the un-transformed x,y
let tx = CGFloat(t) / CGFloat(nPoints) // 0 ... 1
let ty = 0.1 * sin(tx * 2 * CGFloat.pi ) // 0 ... 2π, arbitrary amplitude
// Apply the transform
let x = p1.x + d * (tx * cosa - ty * sina)
let y = p1.y + d * (tx * sina + ty * cosa)
// Add the transformed point to the path
path.addLine(to: CGPoint(x: x, y: y))
}

// Draw the path
context.setStrokeColor(UIColor.blue.cgColor)
context.addPath(path)
context.strokePath()
}
}

let v = MyView(frame: CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 500, height: 500)))

Playground output...

关于swift - 两点之间的正弦波 UIBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com