swift 3 中未显示合并的图像和文本

Not showing merged image and text in swift 3

您好,我是 swift 3 和 Xcode 8 的新手,我在下面的代码中遇到问题 构建成功,它在模拟器中运行良好,但图像和文本未显示 什么我做错了?

import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
   generateImageWithText(text: "HelloWorld")
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@discardableResult
func generateImageWithText(text: String) -> UIImage
{
    let image = UIImage(named: "apple_led.png")!

    let imageView = UIImageView(image: image)
    imageView.backgroundColor = UIColor.black
    imageView.frame = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))

    let label = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 50)))
    label.backgroundColor = UIColor.white
    label.textAlignment = .center
    label.textColor = UIColor.blue
    label.text = text

    UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0);
    imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    label.layer.render(in: UIGraphicsGetCurrentContext()!)
    let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    print(image)
    print(text)
    print(label)
    return imageWithText!
}
}

试试这个

func mergeImageAndText(text: NSString, atPoint: CGPoint) -> UIImage{


        let demoImage = UIImage(named: "test.png")!

        // Setup the font specific variables
        let textColor = UIColor.white
        let textFont = UIFont(name: "Helvetica", size: 14)!

        // Setup the image context using the passed image


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

        // Setup the font attributes that will be later used to dictate how the text should be drawn
        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]



        demoImage.draw(in: CGRect(x: 0, y: 0, width: 50, height:50))



        let rect =  CGRect(x: atPoint.x, y: atPoint.y, width: demoImage.size.width, height: demoImage.size.height)

        // Draw the text into an image

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



        // Create a new image out of the images we have created
        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        // End the context now that we have the image we need
        UIGraphicsEndImageContext()

        //Pass the image back up to the caller
        return newImage!

    }

方法调用:

let imagenew  = self.mergeImageAndText(text: "TEST", atPoint: CGPoint(x: 10, y: 10))