Graphics Reference
In-Depth Information
Figure 4.20
In the faded button on the right, the internal label's border is clearly visible.
This effect is due the way that alpha blending works. When you display a layer with 50%
opacity, each pixel of the layer displays 50% of its own color and 50% of the layer behind
it. That results in the appearance of translucency. But if the layer contains sublayers that are
also displayed at 50% transparency, then when you look through the sublayer, you are
seeing 50% of the sublayer's color, 25% of the containing layer's color, and only 25% of
the background color.
In our example, the button and label both have white backgrounds. Even though they are
both only 50% opaque, their combined opacity is 75%, and so the area where the label
overlaps the button look less transparent than the surrounding part. This serves to highlight
all of the sublayers that make up a control and produces a nasty visual effect.
Ideally, when you set the
opacity
of a layer, you want its entire subtree to fade as if it
were a single layer, without revealing its internal structure. You can achieve this by setting
UIViewGroupOpacity
to
YES
in your
Info.plist
file, but this affects the way that
blending is handled across the whole application, and introduces a small app-wide
performance penalty. If the
UIViewGroupOpacity
key is omitted, its value defaults to
NO
on iOS 6 and earlier (though the default may change in a future iOS release).
Alternatively, you can implement group opacity for a specific layer subtree by using a
CALayer
property called
shouldRasterize
(see Listing 4.7). When set to
YES
, the
shouldRasterize
property causes the layer and its sublayers to be collapsed into a
single flat image
before the opacity is applied
, thereby eliminating the blending glitch (see
Figure 4.21).
In addition to enabling the
shouldRasterize
property, we've modified the layer's
rasterizationScale
property. By default, all layers are rasterized at a scale of 1.0, so
if you use the
shouldRasterize
property, you should always ensure that you set the