如何在 Swift 中将文本(字符串)转换为图像(UIImage)



我今天更新了Xcode,cocoa pod,alamofire,alamofireimage,

现在我的代码上有一个关于文本到图像的红色标记。

我是编码的初学者。

func textToImage(drawText text: NSString, 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)
    let textFontAttributes = [
        NSAttributedStringKey.font.rawValue: textFont,
        NSAttributedStringKey.foregroundColor: textColor,
        ] as! [String : Any]
    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
    let rect = CGRect(origin: point, size: image.size)
    text.draw(in: rect, withAttributes: textFontAttributes )
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

利涅的红色品牌

text.draw(in: rect, withAttributes: textFontAttributes )

消息:无法将类型"[字符串:任何]"的值转换为预期的参数类型"[NSAttributedStringKey : Any]?

您的代码存在一些问题。首先不要使用 NSString,Swift 原生字符串类型是 String。其次,您需要将 textFontAttributes 类型指定为 [NSAttributedStringKey: Any],并且不要强制解开结果。将返回类型更改为可选图像 UIImage?还可以在方法完成后使用 defer 结束图形图像上下文。

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()
}

最新更新