iosswiftuiviewdrawrectcatiledlayer

Is it possible to draw a line outside rect bounds in draw(_ rect: CGRect) function in a UIView subclass that is backed by a CATiledLayer?


I have a UIView subclass that is backed by a CATiledLayer, where I override draw(_ rect: CGRect) function for custom drawing. Is it possible to draw a line outside rect bounds?


Solution

  • I just did a test, and no, it seems that you can't draw outside of the rect provided in the call to the draw(_:) function.

    I created a custom Subclass of UIView that overrides draw(_:):

    class CustomView: UIView {
        override func draw(_ rect: CGRect) {
            let drawRect = rect.insetBy(dx: -10, dy: -10)
            let path = UIBezierPath(rect: drawRect)
            UIColor.yellow.setFill()
            path.fill()
        }
    }
    

    And then I added a CustomView to my storyboard. I set up the view in the storyboard with a layer.borderWidth = 2 so you could see the border of the view, and this is what was drawn:

    enter image description here

    My draw(_:) method tried to inset the draw rect by (-10,-10), which makes the rectangle bigger, but no drawing is visible outside of the bounds set in the storyboard.