Skip to content

Instantly share code, notes, and snippets.

@krummler
Last active April 20, 2020 11:17
Show Gist options
  • Save krummler/fce1432ad8b9fcfc853fb91a1acb5115 to your computer and use it in GitHub Desktop.
Save krummler/fce1432ad8b9fcfc853fb91a1acb5115 to your computer and use it in GitHub Desktop.
extension UIImage {
static func buttonBackground(color: UIColor,
borderColor: UIColor,
borderWidth: CGFloat,
cornerRadius: CGFloat) -> UIImage {
let width = max(2, cornerRadius * 2)
let size = CGSize(width: width, height: width)
return UIGraphicsImageRenderer(size: size).image { context in
color.setFill()
context.fill(CGRect(origin: .zero, size: size))
}.roundedBorder(color: borderColor,
width: borderWidth,
radius: cornerRadius)!
}
private func roundedBorder(color: UIColor, width: CGFloat, radius: CGFloat) -> UIImage? {
let format = imageRendererFormat
format.opaque = false
return UIGraphicsImageRenderer(size: size, format: format).image { context in
let ovalPath = UIBezierPath(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: radius)
ovalPath.addClip()
draw(at: .zero)
color.setStroke()
ovalPath.lineWidth = width
ovalPath.stroke()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment