October 5, 2012
Good Friday #6: SKInnerShadowLayer
I’ve fixed the graphical bugs in
SKInnerShadowLayer. See below.
SKInnerShadowLayer is a
CAGradientLayer subclass that adds properties to create an inner shadow on a given layer.
Find at it Github: github.com/khanlou/SKInnerShadowLayer
SKInnerShadowLayer takes the graphical properties of a
CAGradientLayer that let you set the shadow, gradient, and border of a layer, and adds four properities that let you control the look of an inner shadow for the layer.
These properties are:
@property CGColorRef innerShadowColor; @property CGSize innerShadowOffset; @property CGFloat innerShadowRadius; @property CGFloat innerShadowOpacity;
They behave similarly to their drop shadow counterparts.
The technique for drawing the inner shadow is simple. The layer:
- creates a path for rounded rect of the layer
- clips to this rounded rect
- creates a larger path around the rounded rect
- sets the shadow properties
- draws a shadow behind this shape
and this creates the illusion of an inner shadow.
These properties are all fully animatable. There is an example of a layer with an inner shadow opacity animation in the demo app. Being able to easily create animations is the immediate advantage of using
CoreGraphics to draw an inner shadow instead of using an image resource.
There were small bugs with the drawing of the inner shadow, but they were due to the default value for
contentsScale on a
CALayer being set to
1.0 by default, even on Hi-DPI/Retina devices. Setting it to
2.0 fixed the problem. I also found this incredible sentence, from the Apple documentation:
The contentScale default value is 1.0. In certain restricted cases, the value may set the value to 2.0 on hi-dpi devices.