I have created an UIImage extension to create an image from a string (using an icon font). Most of the time it works without any problem, but sometimes it caused the app to crash with a EXC_BAD_ACCESS. This happens both on devices an in the simulator.
How can I find out what is going wrong? Why does it work most of the time and fails only in rare cases?
The code runs on the main thread.
extension UIImage {
static func image(withIconText text: String, font: UIFont, color: UIColor) -> UIImage {
#if os(iOS)
let scale = UIScreen.main.scale
#else
// Watch
let scale = 2.0
#endif
let attributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color,
]
UIGraphicsBeginImageContextWithOptions(CGSize(width: font.pointSize, height: font.pointSize), false, scale)
let textSize = (text as NSString).size(withAttributes: attributes)
let origin = CGPoint(x: (font.pointSize - textSize.width) / 2, y: (font.pointSize - textSize.height) / 2)
let rect = CGRect(origin: origin, size: textSize)
// Crash: Thread 1: EXC_BAD_ACCESS
text.draw(in: rect, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
}