在iOS中截取带有标签和透明背景的视图的屏幕快照,并将其上传到服务器

时间:2018-10-03 08:50:18

标签: ios swift uiimage uigraphicscontext uigraphicsrenderer

我想截图一个视图并从中创建一个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!
}

3 个答案:

答案 0 :(得分:1)

这是由于以下事实:渲染视图时,图像为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)
 }
}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

  

Swift 5 UIImage扩展:具有透明背景的屏幕UIView

  • 这是用于拍摄应该具有.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)
    }

}