fredag den 7. december 2012

iOS - showing only the shadow of a CALayer

I'm recently doing a simple iOS puzzle-game using the Core Animation framework in which the player has to move various pictures into place. The correct locations are visualized by the blurred shadows of the pictures.

To achieve this without having to manually draw the shadows in GIMP (which happens to be my favorite open-source image manipulation program) I came up a very simple use of CALayer's shadow property: Simply offset the layer by, say, twice the screen width and the shadow by twice the screen width in the opposite direction, and voila! Only the shadow of your CALayer is visible - in whatever color you would like and with whatever blur factor you wish.

Here's some code:

layer.bounds = CGRectMake(0.0f, 0.0f, pictureRect.size.width, pictureRect.size.height);
layer.position = CGPointMake(pictureRect.origin.x + (screenWidth * 2.0f), pictureRect.origin.y);
layer.contents = (id)image.CGImage;
    
layer.shadowOffset = CGSizeMake(-(screenWidth * 2.0f), 0.0f);
layer.shadowRadius = 0.0f;
layer.shadowColor = [UIColor blackColor].CGColor;
layer.shadowOpacity = 0.7f;


No need to start up GIMP when one can produce the same effect in code! :-)

Ingen kommentarer:

Send en kommentar