将文本写入透明 UIImage

Writing text to transparent UIImage

我想在完全透明的图像(到处都是 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)
}

无论我做什么,背景都是白色的。

我已经在 playgroung 中测试了您的代码,它可以正常工作

所以原因是 Apple Gallery 表示的 Alpha 通道。好像不支持

尝试转换为 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)
        }
    }
}