0

我正在尝试通过向图像添加文本来编辑图像,但我从这篇文章中获得的代码不起作用:如何在 Objective-C (iOS) 中的图像上写入文本?

我的图像编辑代码如下所示:

func addTextToImage(image:UIImage, text:NSString, pointof: CGPoint) -> UIImage{

    let font:UIFont = UIFont.boldSystemFontOfSize(12)

    let dict:NSDictionary = [NSFontAttributeName : font]

    UIGraphicsBeginImageContext(image.size)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
    let rect: CGRect = CGRectMake(pointof.x, pointof.y, image.size.width, image.size.height)
    let color: UIColor = UIColor.whiteColor()
    text.drawInRect(CGRectIntegral(rect), withAttributes:dict)

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

然后我使用该textViewDidChange方法将文本添加到图像中,但它不起作用:

func textViewDidChange(textView: UITextView){
    backgroundImage.image = addTextToImage(imageToView, text: textViewer.text, pointof: CGPointMake(0, 0))
}

任何关于我做错了什么的建议将不胜感激。

4

1 回答 1

0
func addTextToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage
{
    let textColor = UIColor.blue

    let textFont = UIFont(name: "ChalkboardSE-Regular", size: 26)!

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: 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!
}
于 2017-12-07T06:42:29.547 回答