UILabel 渲染到 UIImage

UILabel rendering in to UIImage

我正在尝试将 UILabel 放入 UIImage,我能够更改标签框的宽度和高度 但是我无法更改 X 和 Y 值,请有人帮我更改 x 和 y 值。

这是我调用方法的方式

self.imfFront.image = generateImageWithText(text: "Hello World !")

方法在这里

func generateImageWithText(text: String) -> UIImage
{
    let image = UIImage(named:"img_forest")!
    let imageView = UIImageView(image: image)
    imageView.backgroundColor = UIColor.clear
    imageView.frame = CGRect(x:0, y:0, width:image.size.width, height:image.size.height)

    let label = UILabel(frame: CGRect(x:50, y:50, width:image.size.width-50, height:image.size.height-50))
    label.backgroundColor = UIColor.lightGray
    label.textAlignment = .center
    label.textColor = UIColor.white
    label.text = text

    UIGraphicsBeginImageContext(imageView.bounds.size)
    imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    label.layer.render(in: UIGraphicsGetCurrentContext()!)
    let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    return imageWithText!
}

下面是参考图片

Quartz2d 使用不同的 co-ordinate 系统,原点在左下角。因此,您可以绘制它而不是渲染...

let rect = imageView.bounds.size
UIGraphicsBeginImageContext(rect)
imageView.draw(imageView.bounds.size)
label.draw(rect)

//    imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
//     label.layer.render(in: UIGraphicsGetCurrentContext()!)

let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();

如果您要像这样指定 labelRect

let labelRect = CGRect(x: 50, y: 50, width: image.size.width - 100, height: image.size.height / 16)
let label = UILabel(frame: labelRect)

而不是:

label.layer.render...

你会写:

label.drawHierarchy(in: labelRect, afterScreenUpdates: true)

那么在 UIImageView 中显示的结果图像将如下所示:

对 labelRect 的 x- 或 y-value 的任何更改都会移动标签。

备注:请记住,您是在图像上绘图,因此标签字体的实际大小取决于图像的分辨率。根据您的要求,这可能是您的意图,也可能不是。