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

I have a UIImageView that I want to add a shadow. I want the apple to have this property, but for this we need to do a lot for programmers, so I need to ask this question.

+63
iphone uiimageview shadow
Jan 11 '10 at 19:51
source share
5 answers

There is a better and easier way to do this. UIImageView inherits from UIView, so it has a layer property. You can access the shadow properties of the shadow and bam, you have the shadow.

If you have UIImageView as an IBOutlet for the nib file, you can just implement awakeFromNib for example.

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; } 

Do not forget #import "QuartzCore/CALayer.h"




There are several ways you can use Swift. Create a class extension, subclass, or imageView instance. In whatever way, this process does not change when the property of layer tags changes.

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 } 
+194
Oct 01 '10 at 23:14
source share

The simplest thing is to 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]; 

Make sure “Lifting Clips” is turned off to view

+10
Jan 11
source share

in addition to this, if you want to make a white border and shadow, you can use this code:

 //shadow part imageView.layer.shadowColor = [UIColor blackColor].CGColor; imageView.layer.shadowOffset = CGSizeMake(0, 1); imageView.layer.shadowOpacity = 1; imageView.layer.shadowRadius = 1.0; //white border part [imageView.layer setBorderColor: [[UIColor whiteColor] CGColor]]; [imageView.layer setBorderWidth: 2.0]; 
+4
May 09 '12 at
source share

Fast solution with extension. A subclass is not required. Call myImage.addShadow() with viewDidLoad() . This should work for UIView and UIImageView .

 extension UIView { func addShadow() { layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowOpacity = 0.5 layer.shadowRadius = 5 clipsToBounds = false } } 
+4
Feb 10 '17 at 13:36 on
source share

UIView set shadowlayer

and addSubview: your imageView

-2
Aug 27 '13 at 9:38 on
source share



All Articles