Custom UIView with transparent background

In this post I will describe how to add custom UIView objects with transparent bacgground to your project.

In the Things Speak app I have a custom UIView where the different charts are presented. It is a really simple one, two subviews are being added with the charts to a standard UI element. The topmost subview is expected to have transparent bacground to not hide the other one, while the lower one has extra contents like chart guide lines, scales, etc. I nearly spent 3 hours to find what the problem is, based on the forums it seemed no one had the same problem before. Now, that I know what is the solution, it is pretty logic.

To demonstrate it, I created a small example. Full source code can be downloaded from here.

First, let’s see the custom view. It has a draw() function where a circle or a rectangle will be drawn. On a custom background color with custom drawing color.

Let’s create an instance of this view with a red circle on a white background.

The result will be the same as we expected:

Adding the second view with 50% transparency black background and a blue rectangle:

The result will be this:

Pretty good, but we would like to see the circle and the expected result would be a grey-ish background through a semi-transparent view. This black is definitely not what we want.

The key is to set the isOpaque parameter of the window. According to Apple if the opaque parameter is true, for the best user experience and for better performance anything covered by the view will be fully skipped from rendering, even if the background was set to transparent. Actually the set backround will be used instead of anything under it. If we set white transparent background, the result will be gray, but the circle is not visible.

So change back the background to black and set the isOpaque to false right before we are attaching the second view to the main view:

After the isOpaque has been set, the output is now ok:

Finally, to support rotation, add this function to your main view: