Last active
June 25, 2022 09:53
-
-
Save AndreyAnt/d08f598be6a0b5dc1d7b55f0b537b4e3 to your computer and use it in GitHub Desktop.
Implementation Idea of rounded corners image view.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
@IBDesignable class AvatarImageView: UIImageView { | |
@IBInspectable var shadowRadius: CGFloat = 10.0 { | |
didSet { | |
setNeedsDisplay() | |
} | |
} | |
@IBInspectable var shadowColor: UIColor = .black { | |
didSet { | |
setNeedsDisplay() | |
} | |
} | |
private var _image: UIImage? | |
override var image: UIImage? { | |
get { | |
return _image | |
} | |
set { | |
_image = newValue | |
layer.contents = nil | |
contentLayer.contents = newValue?.cgImage | |
} | |
} | |
private let shadowLayer = CAShapeLayer() | |
private let contentLayer = CALayer() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
layer.insertSublayer(contentLayer, at: 0) | |
layer.insertSublayer(shadowLayer, below: contentLayer) | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
layer.insertSublayer(contentLayer, at: 0) | |
layer.insertSublayer(shadowLayer, below: contentLayer) | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
contentLayer.frame = bounds | |
contentLayer.cornerRadius = bounds.width/2 | |
contentLayer.masksToBounds = true | |
shadowLayer.path = UIBezierPath(ovalIn: bounds).cgPath | |
shadowLayer.fillColor = UIColor.clear.cgColor | |
shadowLayer.shadowColor = UIColor.black.cgColor | |
shadowLayer.shadowPath = shadowLayer.path | |
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 1.0) | |
shadowLayer.shadowOpacity = 0.5 | |
shadowLayer.shadowRadius = shadowRadius | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment