CGImageCreate: 无效图像 alphaInfo: kCGImageAlphaNone。它应该是 kCGImageAlphaNoneSkipLast

wei*_*ard 7 core-graphics ios swift uigraphicsimagerenderer

我正在尝试将 UIVIew 捕获为图像,然后我可以对其进行操作。我有在 Xcode 11.7/simulator(运行 iOS 13.7)中工作的代码,但是抛出这个错误:

CGImageCreate: 无效图像 alphaInfo: kCGImageAlphaNone。它应该是 kCGImageAlphaNoneSkipLast

在实际设备上运行会导致崩溃。

任何想法如何在没有 alpha 的情况下创建此图像或事后将其删除?

extension UIView  {
    // render the view within the view's bounds, then capture it as image
  func asImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image(actions: { rendererContext in
        layer.render(in: rendererContext.cgContext)
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

它从这段代码中被调用:

@IBAction func reactionListButtonTapped(_ sender: UIButton) {
  guard let reactionVC = storyboard?.instantiateViewController(withIdentifier: "ReactionViewController")
    as? ReactionViewController else {
      
    assertionFailure("No view controller ID ReactionViewController in storyboard")
    return
  }

  // take a snapshot of current view and set it as backingImage
  reactionVC.backingImage = self.view.asImage()

  self.present(reactionVC, animated: false, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。