Reputation: 31
I'm trying to convert a view on my scene to a UIImage to be used in snapchats API for stickers. When the image is generated from the view, all is right except for the white background. I do not want a background.
I have tried converting the image to jpeg and checked that the background is actually clear.
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
}
Compiles and runs, just has a white background to the UIView where it should be clear
Upvotes: 2
Views: 1141
Reputation: 1264
I'm not familiar with SCSDK
but this is the extension I use for turning UIViews into images, and it works fine for transparent backgrounds. Assuming you aren't set on using that library, you could try this method.
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)!)
}
}
Call with:
let image = UIImage(from: myView)
Let me know if that works for you.
Upvotes: 1