首页 > 解决方案 > Merge UIImage with UILabel into one UIImage, Swift

问题描述

I am trying to "merge" an UIImage with a UILabel into one UIImage, for that I wrote a function everything works fine except that the Label does not get added to the Current Graphics Context. I would appreciate your help!

    func textToImage(drawText: String, inImage: UIImage, atPoint: CGPoint) -> UIImage{

    // Setup the image context using the passed image
    UIGraphicsBeginImageContext(inImage.size)

    // Put the image into a rectangle as large as the original image

    inImage.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: inImage.size.width, height: inImage.size.height)))

    // Create a point within the space that is as bit as the image
    let rectPos = CGPoint(x: atPoint.x, y: atPoint.y)
    let rectSize = CGSize(width: inImage.size.width, height: inImage.size.height)
    let rect = CGRect(origin: rectPos, size: rectSize)

    // Draw the text into an image
    let label = UILabel()
    label.text = drawText
    label.textColor = .white
    label.font = UIFont(name: "Helvetica Bold", size: 12)!

    label.drawText(in: rect)
    // 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!
}

标签: iosswiftxcodebitmapuiimage

解决方案


您的代码的问题是 UIKit(UILabel 用法)试图在自己的上下文中绘制内容。您需要在相同的上下文中绘制文本 + 图像以获得所需的结果。

试试这个来接收结果图像:

func textToImage(drawText text: NSString, inImage image: UIImage) -> UIImage
{

    UIGraphicsBeginImageContext(image.size)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))

    let font=UIFont(name: "Helvetica-Bold", size: 8)!

    let paraStyle=NSMutableParagraphStyle()
    paraStyle.alignment=NSTextAlignment.center

    let attributes = [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:font, NSAttributedStringKey.paragraphStyle:paraStyle]

    let height = font.lineHeight

    let y = (image.size.height-height) / 2

    let strRect = CGRect(x: 0, y: y, width: image.size.width, height: height)

    text.draw(in: strRect.integral, withAttributes: attributes)

    let result=UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return result!
}

@IBAction func touchTest(_ sender: Any)
{
    let button = sender as! UIButton
    let image = self.textToImage(drawText: "my text", inImage: UIImage.init(named: "circle")!)
    button.setBackgroundImage(image, for: UIControlState.normal)
}

推荐阅读