2017-10-15 3 views
1

J'ai fait la mise à jour de Xcode, pod de cacao, alamofire, alamofireimage aujourd'hui,Problème de texte à image rapide. Impossible de convertir la valeur de type '[String: Any]' en type d'argument attendu '[NSAttributedStringKey: Any]?'

maintenant j'ai une marque rouge sur mon code sur le texte à l'image. Je suis un débutant avec le codage.

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

la Comme marque rouge en ligne

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

avec le message: Impossible de convertir la valeur de type '[Chaîne: Tous]' type d'argument attendu '[NSAttributedStringKey: Tout]?

+0

changer votre type textFontAttributes à '[NSAttributedStringKey: Tous]' –

+0

'laisser textFontAttributes: [NSAttributedStringKey: Tous] = [ .font: textFont, .foregroundColor: textColor]' –

+0

Merci, il fonctionne à présent. 'Let textFontAttributes: [NSAttributedStringKey: Tous] = [ NSAttributedStringKey (rawValue: NSAttributedStringKey.font.rawValue): textFont, NSAttributedStringKey.foregroundColor: textColor, ]' – Geoff

Répondre

0

Il y a quelques problèmes avec votre code. N'utilisez d'abord pas NSString, le type de chaîne native Swift est String. Deuxièmement, vous devez spécifier votre type textFontAttributes comme [NSAttributedStringKey: Any] et ne forcez pas le déploiement du résultat. Changer le type de retour en image facultative UIImage? Vous pouvez également utiliser différer pour mettre fin au contexte d'image graphique lorsque votre méthode se termine. juste

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