Swift文本到图像问题。无法转换类型的值' [String:Any]'预期的参数类型' [NSAttributedStringKey:Any]?'

时间:2017-10-15 13:24:36

标签: swift swift4 alamofireimage

我今天更新了Xcode,可可豆荚,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!
}
在ligne的红色品牌纪念

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

带有消息:无法转换类型的值' [String:Any]'预期的参数类型' [NSAttributedStringKey:Any]?'

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。首先不要使用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()
}