LoginSignup
3
5

More than 5 years have passed since last update.

Swift 3 Playgroundで曲線波形を描画する

Last updated at Posted at 2017-02-23

Screen Shot 2017-02-23 at 20.17.58.png

Xcode 8.2を使用

import UIKit
import PlaygroundSupport

// ベースとなるUIViewを作成
var dim: CGFloat = 500
let container = UIView(frame: CGRect(x: 0, y: 0, width: dim, height: dim))
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = container

// 曲線を描画するためのUIViewサブクラス
class MyView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 200))

        let span: CGFloat = 20
        var pos1 = path.currentPoint

        for idx in 1...25 {
            let plotX: CGFloat = span * CGFloat(idx)
            let plotY: CGFloat = (idx % 2 == 0) ? 200 : 300
            let pos = CGPoint(x: plotX, y: plotY)
            // 曲線の追加と調整
            var pos2 = pos
            pos1.x += span * 0.5
            pos2.x -= span * 0.5
            path.addCurve(to: pos, controlPoint1: pos1, controlPoint2: pos2)
            pos1 = pos
        }

        path.lineWidth = 4.0
        UIColor.white.setStroke()
        path.stroke()
    }
}

let view = MyView(frame: container.bounds)
view.backgroundColor = UIColor.red
container.addSubview(view)
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5