I am trying to create a UIView
with text
(the text
may keep changing) on top of it. I want only the text
part of that UIView
to be transparent so that we can see through the text. In other words, I want the text part to show whatever is in the superview
of the UIView
. I spent a lot of time on it but have not figured it out yet. Anyone has ideas how to do that?

- 118,658
- 15
- 128
- 151

- 33
- 5
-
What have you tried? Why not change the alpha attribute of your text in interface builder. – evan.stoddard Aug 28 '13 at 19:09
3 Answers
You could create a CALayer
, clear it to transparent and then render the text into it (must be opaque). Then, set that layer as the mask
of the view.layer
.

- 118,658
- 15
- 128
- 151
What you want to do isn't trivial. But it's possible with a little work.
In a nutshell, to make the text transparent you need to create a CALayer with the text cut out, then use that as a mask to the current CALayer.
Start by creating an image of the text. You can just create a UILabel, with black text on a white background. The black will be what becomes transparent when we're done. The white background should be the same size as the UIView you're going to apply it to.
Now get an image of this text using UIGraphicsGetImageFromCurrentImageContext(). There should be lots of examples of how to do this here on SO.
Now use that image to create a new mask layer. Do this by creating a new CALayer object and assigning the image.CGImage to the layer's 'contents' property.
Now assign that layer to the 'mask' property of your UIView's layer. This view could be just an empty view with a white 'backgroundColor'.
If everything goes as planned, the black parts of the mask (the text) will make the white UIView transparent. Then just lay it over an image.
Keep in mind masks don't animate. So changing this mask will require a bunch more extra work if you want to transition smoothly to other titles.

- 8,795
- 1
- 46
- 50
My first thought is to subclass the view and implement draw:
method. there you can fill the view with whatever color you want and then use drawText:inRect:
( or whatever is called) to draw the text with a clear color over it. This should achieve the effect you want.

- 2,201
- 2
- 18
- 23