Swift text to image issue。无法将类型'[String:Any]'的值转换为期望的参数类型'[NSAttributedStringKey:Any]?'

问题描述:

我今天更新了Xcode,可可豆荚,alamofire,alamofireimage,Swift text to image issue。无法将类型'[String:Any]'的值转换为期望的参数类型'[NSAttributedStringKey:Any]?'

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

我是一个编码的初学者。

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! 
} 

红色劳斯莱斯COMME在LIGNE

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

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

+0

只是改变你的textFontAttributes类型'[NSAttributedStringKey:任何]'' –

+0

让textFontAttributes:[NSAttributedStringKey:任何] = [ .font:TEXTFONT, .foregroundColor:文字颜色]' –

+0

谢谢你,它的工作现在。 '让textFontAttributes:[NSAttributedStringKey:任何] = [ NSAttributedStringKey(rawValue:NSAttributedStringKey.font.rawValue):TEXTFONT, NSAttributedStringKey.foregroundColor:文字颜色, ]' – Geoff

您的代码有几个问题。首先不要使用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() 
}