views:

1427

answers:

2

I have a UIImageView that I want to add a shadow behind. I wish that apple had that as a property but they have to make lots of things hard for us programmers so I need to ask this question.

+3  A: 

The simplest thing to do is add a shadow layer to your image view:

CALayer             *layer = [CALayer layer];
CGRect              bounds = self.bounds;

layer.bounds = bounds;
layer.position = CGPointMake(bounds.size.width / 2 + 3, bounds.size.height / 2 + 3);
layer.backgroundColor = [UIColor colorWithWhite: 0.25 alpha: 0.55].CGColor;
layer.zPosition = -5;

[self.layer addSublayer: layer];

Be sure "Clip Subviews" is turned off for the view

Ben Gottlieb
why are you making a CGRect *bounds when you can just set the layer's bounds to self.bounds? And where does the shadow come into place?
Jaba
I create a temp variable for readability; typing out self.bounds is a little longer than just bounds, and makes the code a little less readable. This layer IS the shadow. Of course, this presupposes you've got a square image; if you're doing a non-rectangular image, you'll have to use a custom image mask.
Ben Gottlieb
Well I want to have it faded and I don't know how I would do that. Pleas help!
Jaba
Fading is a separate task entirely. If you want to have a custom shadow (something other than a simple dark rectangle behind your image), you should take the image, make it into a mask (ie, all black and transparent), apply your fade, and then draw it behind the original, using either Quartz, or sticking into a layer.
Ben Gottlieb
+3  A: 

there's a better and easier way to do this. UIImageView inherits from UIView so it has a layer property. You can access the layer's shadow properties and bam, you got a shadow.

if you have the UIImageView as an IBOutlet to a nib file, you can just implement the awakeFromNib e.g.

- (void)awakeFromNib {
imageView.layer.shadowColor = [UIColor purpleColor].CGColor;
imageView.layer.shadowOffset = CGSizeMake(0, 1);
imageView.layer.shadowOpacity = 1;
imageView.layer.shadowRadius = 1.0;
}

hope this helps even though it's been 8 months :P

alex n