代码之家  ›  专栏  ›  技术社区  ›  Geoff

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

  •  1
  • Geoff  · 技术社区  · 8 年前

    我今天更新了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!
    }
    

    ligne中的红色品牌comme

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

    消息:无法将类型为“[String:Any]”的值转换为预期的参数类型“[NSAttributedStringKey:Any]?”

    1 回复  |  直到 4 年前
        1
  •  0
  •   Leo Dabus    8 年前

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