churabou / iOS-develop-blog

0 stars 0 forks source link

4月23日(月) #9

Open churabou opened 6 years ago

churabou commented 6 years ago
class TestLayer: CALayer {

    override func draw(in ctx: CGContext) {
        ctx.setFillColor(UIColor.blue.cgColor)
        ctx.fill(bounds)
    }
}
class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

        let  test = TestLayer()
        test.frame = view.bounds
        test.backgroundColor = UIColor.red.cgColor
        view.layer.addSublayer(test)
        view.backgroundColor = .orange
        test.setNeedsDisplay()
   }
}

viewに表示される色は青

    test.setNeedsDisplay()を呼ぶタイミングを変えても青かった。
churabou commented 6 years ago

コンテクストであるrect以外を塗りつぶしたい。 mask使うしかない?


class MaskLayer: CALayer {

    var maskRect: CGRect = .zero

    override func draw(in ctx: CGContext) {
        ctx.setFillColor(UIColor.black.cgColor)

        let topRect = CGRect(x: 0, y: 0, width: bounds.width, height: maskRect.minY)
        let leftRect = CGRect(x: 0, y: maskRect.minY, width: maskRect.minX, height: maskRect.height)
        let rightRect = CGRect(x: maskRect.maxX, y: maskRect.minY, width: bounds.width-maskRect.maxX, height: maskRect.height)

        let bottomRect = CGRect(x: 0, y: maskRect.maxY, width: bounds.width, height: bounds.height-maskRect.maxY)

        ctx.fill(topRect)
        ctx.fill(leftRect)
        ctx.fill(rightRect)
        ctx.fill(bottomRect)
    }
}
churabou commented 6 years ago
    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        var size = radius * 2
        var rect = CGRect(x: (bounds.width-size) / 2,
                          y: (bounds.height-size) / 2,
                          width: size,
                          height: size)

        context.setFillColor(borderColor.cgColor)
        context.fillEllipse(in: rect)

        size -= (borderWidth*2)
        rect = CGRect(x: (bounds.width-size) / 2,
                      y: (bounds.height-size) / 2,
                      width: size,
                      height: size)
        let bgColor: UIColor = backgroundColor ?? .white
        context.setFillColor(bgColor.cgColor)
        context.fillEllipse(in: rect)
    }