将具有清晰背景色的UIView转换为UIImage会为生成的图像添加白色背景色

时间:2019-06-07 17:17:06

标签: swift

我正在尝试将场景中的视图转换为UIImage,以用于gmails API的贴纸中。从视图生成图像时,除白色背景外,其他所有内容均正确。我不想要背景。

我尝试将图像转换为jpeg并检查背景是否真正清晰。

    let renderer = UIGraphicsImageRenderer(size: contentView.bounds.size)        
    let image = renderer.image { ctx in
        contentView.drawHierarchy(in: contentView.bounds, afterScreenUpdates: true)
    }
    let imageData = image.jpegData(compressionQuality: 0.75)!




    let stickerImage = UIImage(data:imageData,scale:1.0)!
    //let stickerImage = /* Prepare a sticker image */
    let sticker = SCSDKSnapSticker(stickerImage: stickerImage)
    /* Alternatively, use a URL instead */
    // let sticker = SCSDKSnapSticker(stickerUrl: stickerImageUrl, isAnimated: false)

    /* Modeling a Snap using SCSDKNoSnapContent */
    let snap = SCSDKNoSnapContent()
    snap.sticker = sticker /* Optional */
    snap.caption = "Snap on Snapchat!" /* Optional */
    snap.attachmentUrl = "https://www.snapchat.com"
    view.isUserInteractionEnabled = false
    snapAPI.startSending(snap) { [weak self] (error: Error?) in
        self?.view.isUserInteractionEnabled = true

        // Handle response
    }

编译并运行,只是UIView带有白色背景,应该将其清除

1 个答案:

答案 0 :(得分:0)

我对0 VARCHAR(11)^VARCHAR(2)^VARCHAR(105)^STRING 1 VARCHAR(87)^VARCHAR(4)^VARCHAR(73) Name: col3, dtype: object 不熟悉,但这是我用来将UIViews转换为图像的扩展名,并且对于透明背景也很好用。假设您尚未开始使用该库,则可以尝试此方法。

SCSDK

致电:

extension UIImage {

    /// Creates a UIImage 'snapshot' of a UIView.
    convenience init(from view: UIView) {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: (image?.cgImage)!)
    }

}

让我知道这是否对您有用。