gpt4 book ai didi

swift - 用频率绘制正弦波?

转载 作者:可可西里 更新时间:2023-11-01 00:36:06 26 4
gpt4 key购买 nike

我正在绘制正弦波的一个周期:

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))
}

Globals.sharedInstance.palleteGlowGreen.setStroke()
path.stroke()

我会怎样:

  1. 为相同的宽度绘制多个句点(现在是 0-360)
  2. 动态更改数字 1(周期数),以便您看到波浪挤压。

最佳答案

只需将角度乘以周期:

@IBDesignable
class SineWaveView: UIView {

@IBInspectable
var graphWidth: CGFloat = 0.90 { didSet { setNeedsDisplay() } }

@IBInspectable
var amplitude: CGFloat = 0.20 { didSet { setNeedsDisplay() } }

@IBInspectable
var periods: CGFloat = 1.0 { didSet { setNeedsDisplay() } }

override func draw(_ rect: CGRect) {
let width = bounds.width
let height = bounds.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 * periods, by: 5.0) {
let x = origin.x + angle/(360.0 * periods) * width * graphWidth
let y = origin.y - sin(angle/180.0 * .pi) * height * amplitude
path.addLine(to: CGPoint(x: x, y: y))
}

Globals.sharedInstance.palleteGlowGreen.setStroke()
path.stroke()
}

}

顺便说一句,通过调用 setNeedsDisplay 更改 periods,这意味着当您更新 periods 时,图表将自动重新绘制。


并且,与其遍历度数,然后将所有内容转换回弧度,我可能只保留弧度:

override func draw(_ rect: CGRect) {
let width = bounds.width
let height = bounds.height

let origin = CGPoint(x: width * (1 - graphWidth) / 2, y: height * 0.50)
let maxAngle: CGFloat = 2 * .pi * periods
let iterations = Int(min(1000, 100 * periods))

let point = { (angle: CGFloat) -> CGPoint in
let x = origin.x + angle/maxAngle * width * self.graphWidth
let y = origin.y - sin(angle) * height * self.amplitude
return CGPoint(x: x, y: y)
}

let path = UIBezierPath()
path.move(to: point(0))

for i in 1 ... iterations {
path.addLine(to: point(maxAngle * CGFloat(i) / CGFloat(iterations)))
}

Globals.sharedInstance.palleteGlowGreen.setStroke()
path.stroke()
}

关于swift - 用频率绘制正弦波?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411198/

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