Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create a shadow behind a UIImageView

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.

like image 819
Jab Avatar asked Jan 11 '10 19:01

Jab


People also ask

How do you add a shadow to a storyboard?

Go to the Storyboard. Add a Button to the main view and give it a title of "Shadow Tutorial". Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints. The Storyboard should look like this.


1 Answers

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.

Objective-C

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

Don't forget to #import "QuartzCore/CALayer.h"


For Swift, you can go about it multiple ways. Create a class extension, subclass, or an imageView instance. Whichever the way, the process is the same in modifying the layers shadow property.

Swift 3

override func awakeFromNib() {     super.awakeFromNib()      imageView.layer.shadowColor = UIColor.purple.cgColor     imageView.layer.shadowOffset = CGSize(width: 0, height: 1)     imageView.layer.shadowOpacity = 1     imageView.layer.shadowRadius = 1.0     imageView.clipsToBounds = false } 
like image 191
Alex Nguyen Avatar answered Oct 19 '22 22:10

Alex Nguyen