将文本写入透明 UIImage
Posted
技术标签:
【中文标题】将文本写入透明 UIImage【英文标题】:Writing text to transparent UIImage 【发布时间】:2020-08-26 08:04:47 【问题描述】:我想在一个完全透明的图像上写一个文本字符串(到处都是 alpha 0),但它不起作用。如果背景图像的 alpha 为 0,则图像的背景变为白色。以下是我尝试的方法:
extension UIColor
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage
return UIGraphicsImageRenderer(size: size).image rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage
let textColor = UIColor.blue
let textFont = UIFont(name: "Helvetica Bold", size: 40)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : 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!
然后:
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
let inImage = UIColor.black.withAlphaComponent(0).image(CGSize(width: 800, height: 800))
//Even tried inImage = UIImage(named: "Transparent") where Transparent.png is fully transparent image! //
let image = textToImage(drawText: "Test String", inImage: inImage, atPoint: CGPoint(x: 0, y: 0))
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
不管我做什么,背景都是白色的。
【问题讨论】:
对我来说,您的代码工作得很好,也许您正在保存为 jpeg 而不是支持 alpha 通道的 png? 好吧,事实证明 UIImageWriteToSavedPhotosAlbum 不会将具有完整 alpha 的图像保存到照片库,因为默认情况下它是 jpeg。在 UIImageView 上尝试过并且工作正常! 【参考方案1】:尝试转换为 png
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
let inImage = UIColor.black.withAlphaComponent(0).image(CGSize(width: 800, height: 800))
//Even tried inImage = UIImage(named: "Transparent") where Transparent.png is fully transparent image! //
let image = textToImage(drawText: "Test String", inImage: inImage, atPoint: CGPoint(x: 0, y: 0))
self.image.image = image
if let pngdata = image.pngData()
if let newImage = UIImage(data: pngdata)
UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
【讨论】:
【参考方案2】:我已经在 playgroung 中测试了你的代码,它可以正常工作
所以原因是 Alpha 通道的 Apple Gallery 表示。好像不支持
【讨论】:
好的,所以按照此代码将 png 保存到照片库,它可以工作 - ***.com/questions/1489250/…以上是关于将文本写入透明 UIImage的主要内容,如果未能解决你的问题,请参考以下文章
将文本创建为位图的工具(消除锯齿文本、自定义间距、透明背景)
PB高手们请赐教!PB能使动态文本框背景透明吗?诸如“mle_1”控件,数据窗口背景能透明也行!见详述~