用频率绘制正弦波?

时间:2016-11-03 21:04:00

标签: swift uibezierpath

我正在画一段正弦波:

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(句点数),以便看到波浪压缩。

1 个答案:

答案 0 :(得分:5)

只需将angle乘以periods

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

}

顺便说一句,通过periods来电setNeedsDisplay进行更改,这意味着当您更新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()
}