LoginSignup
7
3

More than 5 years have passed since last update.

チェック柄(市松模様)を描画するカスタムView

Posted at

はじめに

こんにちは:leaves:
UICollectionViewCellが選択状態の時に使えるデザインを探していて、
画像を使わずにUIViewdrawRectを利用すると軽いという事で作ってみたものの、結局使わずに限定公開に埋まっていたので公開してみたいと思います。
柄を描画するアルゴリズムなどあまり知らず調べずに書いてしまったので、間違っていたらごめんなさい。

実装について

green.png

option.png

プロパティ 説明
panelScale 並ぶタイルの個数
panelAColor タイルの色A
panelBColor タイルの色B

ソースコード

CheckPatternView.swift
import UIKit

@IBDesignable class CheckPatternView: UIView {

    @IBInspectable var panelScale: CGFloat = 4
    @IBInspectable var panelAColor: UIColor = UIColor.white
    @IBInspectable var panelBColor: UIColor = UIColor.black

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {
        if panelScale == 0 { return }
        var alternatelyFlg = false
        let panelWidth = frame.size.width / panelScale
        let panelHeight = frame.size.height / panelScale
        var x: CGFloat = 0
        var y: CGFloat = 0
        for _ in 0 ..< Int(panelScale) {
            for _ in 0 ..< Int(panelScale) {
                let path = UIBezierPath(rect: CGRect(x: x, y: y, width: panelWidth, height: panelHeight))
                let color = alternatelyFlg ? panelAColor : panelBColor
                color.setFill()
                path.fill()
                alternatelyFlg = !alternatelyFlg
                x += panelWidth
            }
            x = 0
            if Int(panelScale) % 2 == 0 {
                alternatelyFlg = !alternatelyFlg
            }
            y += panelHeight
        }
    }
}

さいごに

今回は全く関係ないですが、数学を使った幾何学模様やなまこ壁のような複雑な柄をUIBezierPathなどを利用して描けたら面白いかもと思いましたが、その前に数学を勉強し直さなければいけない焦りを感じましたとさ:sweat:

見て頂いてありがとうございます。

7
3
4

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
7
3