简体   繁体   English

Swift:向图像添加文本不起作用

[英]Swift: Adding text to image does not work

I'm trying to edit an image by adding text to it, but the code I got from this post does not work: How to write text on image in Objective-C (iOS)? 我正在尝试通过向其添加文本来编辑图像,但是从本文中获得的代码不起作用: 如何在Objective-C(iOS)中的图像上编写文本?

My image-editing code looks like this: 我的图像编辑代码如下所示:

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
}

And then I use the textViewDidChange method to add the text to the image, but it does not work: 然后,我使用textViewDidChange方法将文本添加到图像中,但是它不起作用:

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

Any suggestions on what I'm doing wrong would be appreciated. 关于我在做什么错的任何建议将不胜感激。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM