使用UIBezierPath在2点之间绘制波浪

时间:2019-01-10 18:56:45

标签: ios swift drawing uibezierpath

我试图给UITableViewCell一个“波浪形”底部,使其看起来像一个“撕纸”效果(用于订单收据)。 我想在单元的整个长度上绘制它。

我在StackOverflow上发现了this解决方案,该解决方案在两点之间创建了一个正弦。

我尝试更改该代码以实现所需的效果(我知道我的代码有很多错误):

    let path = UIBezierPath()
     let origin = CGPoint(x: 0, y: bounds.size.height / 2)
     path.move(to: origin)

      let graphWidth: CGFloat = 0.8  // Graph is 80% of the width of the view
     let amplitude: CGFloat = 0.5   // Amplitude of sine wave is 30% of view

     for angle in stride(from: 1.0, through: bounds.size.width * 5.0, by: 1.0) {
         let x = origin.x + CGFloat(angle/360.0) * bounds.size.width * (360 / (bounds.size.width * 10.0))
         let y = origin.y - CGFloat(sin(angle/180.0 * CGFloat.pi)) * bounds.size.height * amplitude * (360 / (bounds.size.width * 10.0))
         path.addLine(to: CGPoint(x: x, y: y))
     }

我要达到的目标是: wave

这里最好的方法是什么?如果我能获得解决方案之上的工作并且看起来像图像,那将是完美的。如果有人有其他建议,我会敞开心

1 个答案:

答案 0 :(得分:1)

全部归功于vacawama answer。您可以通过以下方式实现,

class SineView: UIView {
    let graphWidth: CGFloat = 0.15
    let amplitude: CGFloat = 0.1

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

        let origin = CGPoint(x: 0, y: height * 0.50)

        let path = UIBezierPath()
        path.move(to: origin)

        var endY: CGFloat = 0.0
        let step = 5.0
        for angle in stride(from: step, through: Double(width) * (step * step), by: step) {
            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))
            endY = y
        }
        path.addLine(to: CGPoint(x: width, y: endY))
        path.addLine(to: CGPoint(x: width, y: height))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.addLine(to: CGPoint(x: 0, y: origin.y))

        UIColor.black.setFill()
        path.fill()
        UIColor.black.setStroke()
        path.stroke()
    }
}

用法

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let size = view.frame.size
        let sineView = SineView(frame: CGRect(x: 0, y: 100, width: size.width, height: 60))
        sineView.backgroundColor = .white
        self.view.addSubview(sineView)
    }
}

输出

enter image description here

您可以使用graphWidthamplitude来随意调整图表。