gpt4 book ai didi

ios - 以更高的分辨率将UILabel渲染为UIImage

转载 作者:行者123 更新时间:2023-12-01 19:33:11 27 4
gpt4 key购买 nike

我正在使用下面的功能来将UILabel渲染为UIImage

func labelToImage(_ label: UILabel) -> UIImage {           
UIGraphicsBeginImageContextWithOptions(CGSize(width: label.frame.size.width*10, height: label.frame.size.height*10), false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
defer { UIGraphicsEndImageContext() }
label.layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
}

但是生成的图像分辨率太低,无法满足我的需要,我需要将其分辨率提高大约10倍。我不想缩放生成的图像,因为它将像素化。

我想缩放UILabel,然后将其渲染为图像。我已经尝试过 CGAffinTransform Scale,但是没有做任何事情。

最佳答案

您需要先缩放标签的框架和字体大小,然后再将其绘制到新的图像上下文中:

func labelToImage(_ label: UILabel) -> UIImage? {
let size = label.frame.size.applying(.init(scaleX: 10, y: 10))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
label.frame.size = size
label.font = label.font.withSize(label.font.pointSize * 10)
defer { UIGraphicsEndImageContext() }
label.draw(.init(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}

您还可以扩展UILabel以将其缩放到特定大小或百分比:
extension UILabel {
func scaledImage(to size: CGSize) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.opaque = false
let aspectRatio = size.width/frame.size.width
frame = frame.applying(.init(scaleX: aspectRatio, y: aspectRatio))
font = font.withSize(font.pointSize * aspectRatio)
return UIGraphicsImageRenderer(size: size, format: format).image { _ in
draw(.init(origin: .zero, size: size))
}
}
func scaledImage(by percentage: CGFloat) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.opaque = false
frame = frame.applying(.init(scaleX: percentage, y: percentage))
font = font.withSize(font.pointSize * percentage)
return UIGraphicsImageRenderer(size: frame.size, format: format).image { _ in
draw(.init(origin: .zero, size: frame.size))
}
}
}

游乐场测试:
let label = UILabel(frame: .init(origin: .zero, size: .init(width: 200, height: 30)))
label.text = "StackOverflow"
label.scaledImage(by: 10)

enter image description here

关于ios - 以更高的分辨率将UILabel渲染为UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61215952/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com