Reputation: 1123
I'm trying to create a custom UIImageView class that accomplishes two things, it makes the image view round and add a shadow to it.
This is what i have:
RoundImage.swift
class RoundImage: UIImageView {
override func awakeFromNib() {
}
func setImageAndShadow(image: UIImage) {
self.image = image
self.superview?.layoutIfNeeded()
print("Image size \(self.frame.size)")
self.clipsToBounds = true
layer.masksToBounds = true
layer.cornerRadius = self.frame.height / 2
layer.shadowOffset = CGSize(width: 0, height: 3.0)
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.7
layer.shadowRadius = 4
}
}
ViewController.Swift
Class ViewController : UIViewController {
@IBOutlet weak var userImageView: RoundImage!
override func viewDidLoad() {
self.userImageView.setImageAndShadow(image: User.sharedInstance.profileImage!)
}
}
As a result of this a get a round image in the app, but there's no shadow in it.
Thanks in advance for any help.
Upvotes: 1
Views: 3729
Reputation: 2660
Swift 3 You can use CAShapeLayer:
func setImageAndShadow(image: UIImage, myView : UIView) {
self.image = image
self.superview?.layoutIfNeeded()
print("Image size \(self.frame.size)")
self.clipsToBounds = true
layer.masksToBounds = true
layer.cornerRadius = self.frame.height / 2
let Shape = CAShapeLayer()
let myPath = UIBezierPath(ovalIn: self.frame)
Shape.shadowPath = myPath.cgPath
Shape.shadowColor = UIColor.black.cgColor
Shape.shadowOffset = CGSize(width: 0, height: 3)
Shape.shadowRadius = 7
Shape.shadowOpacity = 0.7
myView.layer.insertSublayer(Shape, at: 0)
}
and in VC
let image = UIImage(named: "IMG_4040.jpg")
self.userImageView.setImageAndShadow(image: image!, myView : view)
Upvotes: 2
Reputation: 7741
You don't see the shadow because it is cropped with cornerRadius. In order to make it visible you should create a UIView with UIImageView inside, apply cornerRadius to UIImageView and shadow to it's container (superview)
Upvotes: 1