Last active
February 7, 2019 08:26
-
-
Save jamesgathu/08c4ae2e1867e59e84f8bfdce09163d5 to your computer and use it in GitHub Desktop.
Make sure the used image is square,
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 CircularImageView: UIImageView { | |
@IBInspectable var lineWidth: CGFloat = 2 | |
@IBInspectable var color: UIColor = UIColor.red | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
if let image = self.image{ | |
self.image = image.cropToCircleWithBorderColor(color: self.color, lineWidth: self.lineWidth) | |
} | |
} | |
} | |
extension UIImage{ | |
func cropToCircleWithBorderColor(color : UIColor, lineWidth : CGFloat) -> UIImage{ | |
let imageRect = CGRect(origin: CGPoint.zero, size: self.size) | |
UIGraphicsBeginImageContext(imageRect.size) | |
if let context = UIGraphicsGetCurrentContext(){ | |
context.addEllipse(in: imageRect) | |
context.clip() | |
self.draw(at: CGPoint.zero) | |
// for adding the stroke | |
context.addEllipse(in: imageRect) | |
color.setStroke() | |
context.setLineWidth(lineWidth) | |
context.strokePath() | |
let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
return newImage! | |
} | |
return UIImage() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment