tumbljack

Subtle effects with CALayer

CALayer has some nice new features available in 3.2

Shadows have become a key element in creating realistic user interfaces for Mac, iPhone and now iPad software. The desktop version of Core Animation shipped with shadows built right into CALayer, making it easier than ever to add them to UI. I’ve hoped for shadows on the iPhone OS for a while, and 3.2 has them.

Setting one up looks something like this..

view.layer.shadowOffset = size;

view.layer.shadowOpacity = opacity;

There’s also a shadowColor property that defaults to black, but can be changed to anything. My favorite part of the UIView/CALayer union is that you can talk directly to the layer styling properties of any view without creating layers manually. In fact, (recent epiphany) there’s rarely a need to ever create a separate CALayer object unless you want projection for 3D effects.

Presumably shadows weren’t previously included with the SDK because they’re expensive. CALayer’s shadow is extremely dynamic, with every property being animatable. Even on the desktop, they’re not cheap. New in 3.2, CALayer has a shouldRasterize flag. Turn this on and the shadow becomes a cached bitmap like everything else, instead of recalculating. This helps compositing performance. When the docs mention “composited directly into the destination“, that means slow. And shouldRasterize is definitely faster.

That’s pretty awesome.

Also, CALayer now has a shadowPath property that takes a CGPathRef. This allows you to create the effect of photorealistic lighting situations in 3D space, using distorted shadows. This is really powerful.

You can set one up using a UIBezierPath like this..

view.layer.shadowPath = bezierPath.CGPath;

The path can be any shape imaginable, and a shadow is created based on filling the shape. Shadow properties come with nice default settings. Just turn up the opacity and adjust the offset for flipped Y and you’re good to go.

I put together a small sample. It’s only a few lines of code.

—-

Update: _Always_ use shadowPath for performance. Only use shouldRasterize to optimize offscreen rendering.


  1. tmdvs reblogged this from tumbljack
  2. tumbljack posted this
To Tumblr, Love Metalab