在 iOS 中截取带有标签和透明背景的视图并上传到服务器

Screenshot a view with label and transparent background in iOS and upload it to server

我想截取一个视​​图并从中创建一个 UIImage。我希望在我的图像中保留视图的透明度属性。我在创建 UIImage 的扩展后尝试了这种方法,但是当上传到服务器时,结果图像中的背景不透明。

如果我做错了什么,请帮助或指出我!!这意味着生成的 png 没有透明度。

class func createTransparentImageFrom(label: UILabel, imageSize: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(imageSize, false, 2.0)
    let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
    currentView.backgroundColor = UIColor.clear
    currentView.addSubview(label)

    currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img!
}

您需要将不透明值设置为 true 以获得透明结果 扩展UIView的透明截图

func screenShot() -> UIImage? {
     UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale)
     self.layer.render(in: UIGraphicsGetCurrentContext()!)
     let img = UIGraphicsGetImageFromCurrentImageContext()
     UIGraphicsEndImageContext()
     return img
 }

这是因为当我们渲染视图时,图像是JPEG/JPG,所以我们需要将其转换为png以获取图层信息。

试试这个:

extension UIImage {
 class func createTransparentPNGFrom(label: UILabel, imageSize: CGSize) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
    let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
    currentView.backgroundColor = UIColor.clear
    currentView.addSubview(label)
    currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    guard let newImg = img else {
        return nil
    }
    guard let imageData = UIImagePNGRepresentation(newImg) else {
        return nil
    }
    return UIImage.init(data: imageData)
 }
}

Swift 5 UIImage extension: screen UIView with transparent background

  • 这是为了截取应该有 .backgroundColor = .clear
  • 的视图

extension UIView {

    func takeSnapshotOfView() -> UIImage? {

        let size = CGSize(width: frame.size.width, height: frame.size.height)
        let rect = CGRect.init(origin: .init(x: 0, y: 0), size: frame.size)

        UIGraphicsBeginImageContext(size)
        drawHierarchy(in: rect, afterScreenUpdates: true)

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        guard let imageData = image?.pngData() else {
           return nil
        }

        return UIImage.init(data: imageData)
    }

}