如何在 Swift 中绘制余弦或正弦曲线? [英] How do I draw a cosine or sine curve in Swift?

查看:156
本文介绍了如何在 Swift 中绘制余弦或正弦曲线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想如何在这个项目中使用 UIBezierPath,但我不知道如何实现这种绘图.我可以画一个圆、圆弧和直线,但我对这个感觉很迷茫.感谢帮助

I've been trying to figure out how to use UIBezierPath for this project, but I don't know how to implement this kind of drawing. I can draw a circle and arcs and straight lines, but I am feeling pretty lost on this one. Appreciate the help

推荐答案

要在名为 pathUIBezierPath 上绘制正弦波,请使用 代码>path.addLine(to:).诀窍是将角度(0360)转换为点的 x 坐标,以及 sin(x) 到一个点的 y 坐标.

To draw a sine wave on a UIBezierPath called path, draw a number of line segments using path.addLine(to:). The trick is to convert the angle (0 to 360) to the x coordinate of a point, and sin(x) to the y coordinate of a point.

这是一个例子:

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

<小时>

这是在 Playground 中运行的:


Here it is running in a Playground:

@Rob 更新了此代码,使其 @IBDesignable 具有 @IBInspectable 属性,此外还添加了 periods 属性.在此处查看他的回答.

@Rob updated this code making it @IBDesignable with @IBInspectable properties in addition to adding a periods property. Check out his answer here.

这篇关于如何在 Swift 中绘制余弦或正弦曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆