Skip to content

Instantly share code, notes, and snippets.

@jamesgathu
Last active February 7, 2019 08:26
Show Gist options
  • Save jamesgathu/08c4ae2e1867e59e84f8bfdce09163d5 to your computer and use it in GitHub Desktop.
Save jamesgathu/08c4ae2e1867e59e84f8bfdce09163d5 to your computer and use it in GitHub Desktop.
Make sure the used image is square,
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