您的代码有一些问题。首先不要使用NSString,Swift本机字符串类型为string。其次,您需要将textFontAttributes类型指定为
[NSAttributedStringKey: Any]
不要强行打开结果。将返回类型更改为可选图像UIImage?当方法完成时,也可以使用“延时到结束”图形图像上下文。
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage? {
let textColor: UIColor = .red
let textFont = UIFont(name: "Arial Rounded MT Bold", size: 24)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
defer { UIGraphicsEndImageContext() }
let textFontAttributes: [NSAttributedStringKey: Any] = [.font: textFont, .foregroundColor: textColor]
image.draw(in: CGRect(origin: .zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
return UIGraphicsGetImageFromCurrentImageContext()
}