Re: CGContext always creating a black rect.


Ben Kennedy
 

On 24 Jul 2021, at 11:37 am, Alex Zavatone via groups.io <zav=mac.com@groups.io> wrote:

Hi. I’m trying to draw a bezier shape in CGContext on a UIView in Swift with a transparent background and the background is always black. Nothing online helps.

Any ideas? I’ve checked .isOpaque, backgroundColor. Nothing I can do to get rid of the black rect background. Any ideas?
Move your `backgroundColor` and `isOpaque` calls to the init method(s). I set up a test project with your code, and that solves the problem.

I was going to make that suggestion before I even tested it, though, because it's an obvious smell to me: there's no need to repeatedly set those properties every time you draw, but rather just once, at setup.

A couple of other code style comments:

- You don't need all the `self.` prefixes.

- The `roundRect(…)` function would be better named as `drawRoundRect(…)`.

- That same function seems like it ought to be pure; i.e., have no side effects -- just draw a rect based on its argument. However, it does math and sets instance variables. If it needs to affect and act on persistent state, it ought to be refactored.

-ben

Join cocoa@apple-dev.groups.io to automatically receive all group messages.