[Swift3] UIImageViewにグリッド線を描画する

前提

要素 バージョン
xcode 8.2.1
Swift 3.0.2
iPhone 6s
iOS 10.2.1

概要

UIImageViewに以下の様な3×3のグリッド線を描画する。

コード

UIViewを画面いっぱいに貼り付けて、以下のカスタムクラスを作成する

class GridView: UIView {

  override func draw(_ rect: CGRect) {
    let path = UIBezierPath()
    path.lineWidth = 1.5

    UIColor.white.setStroke()
    path.move(   to: getPoint(rect, x: 1, y: 0))
    path.addLine(to: getPoint(rect, x: 1, y: 3))
    path.move(   to: getPoint(rect, x: 2, y: 0))
    path.addLine(to: getPoint(rect, x: 2, y: 3))
    path.move(   to: getPoint(rect, x: 0, y: 1))
    path.addLine(to: getPoint(rect, x: 3, y: 1))
    path.move(   to: getPoint(rect, x: 0, y: 2))
    path.addLine(to: getPoint(rect, x: 3, y: 2))
    path.stroke()
  }

  /* UIImage上の指定した区画の座標を取得 */
  private func getPoint(_ rect: CGRect, x: CGFloat, y: CGFloat) -> CGPoint {
    let width = rect.width / 3.0
    let height = rect.height / 3.0
    return CGPoint(x: width * x, y: height * y)
  }

}

備考

  • 一部数値を書き換えることで3×3にかぎらず、N×Nの任意のグリッド線を描画できる

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です