0
votes

I have a custom UIView in which I implement several convenient drawing methods, allowing me to set corner radius of specific corners, draw borders, and use gradients instead of a background color. I achieve this by overriding drawRect(rect:CGRect). However, despite using CGContextClip to clip drawing to the CGPathRef I generate, the background color is always drawn to fill the view's bounds. That is because the view's layer draws before drawRect is called.

Aside from overriding the setter for backgroundColor, are there any other ways to only draw what I am specifying in drawRect? I DO NOT want to mask the layer with a CAShapeLayer or something of the sort. It should still be possible to subclass and draw outside of the layer's bounds.

3
Set the backgroundColor to clear color and override the setter. That's the only thing you can do. Also note property clearsContextBeforeDrawing and opaque.Sulthan
Yeah, I currently use the backgroundColor override method, but I wondered if there was a better way. Doesn't seem to be.GoldenJoe

3 Answers

3
votes

You can change the way the background is drawn through a CALayer subclass.

Calling super.draw in your CALayer subclass will cause the background to be drawn. If you omit this the background will not be drawn. (you will also need to override UIView.draw or the method will not be called)

class CustomDrawingLayer: CALayer {
  override func draw(in ctx: CGContext) {
    // super.draw(in: ctx) don't call to prevent default drawing behaviour

    // custom drawing code
  }
}

When you change the background color of a view to something other than clear, the backing CALayer.isOpaque will be set to true which removes the alpha channel from the layer, if that opaque color is not drawn then the background will be solid black, you can prevent this behaviour by overriding the variable

override var isOpaque: Bool {
    get {
        return false
    }
    set {
        // you can leave this empty...
    }
}

An easier solution to the problem would be to set the background color of the view to clear and draw the background as you want in your view.

-1
votes

You might find luck by setting your view.layer.masksToBounds = true.

-1
votes

Will put [super drawRect:frame] at the end of the drawRect: method works?