用频率绘制正弦波? [英] Draw sine wave with frequency?
本文介绍了用频率绘制正弦波?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在绘制一个正弦波周期:
I am drawing one period of a sine wave with:
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()
我会如何:
- 为相同的宽度(现在是 0-360)绘制多个句点
- 动态更改数字 1(周期数),以便您看到波浪挤压.
推荐答案
只需将 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
时,图表会自动重绘.
By the way, by making a change in periods
call setNeedsDisplay
, that means that when you update periods
, the graph will be automatically redrawn.
而且,与其遍历度数,然后将所有内容都转换回弧度,我可能只保留弧度:
And, rather than iterating through degrees, but then converting everything back to radians, I might just stay in radians:
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()
}
这篇关于用频率绘制正弦波?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文