'How I can save a view combined with my Image Data in SwiftUI
I am working on a sticker maker app. So used ZStack to add text on the photo. I want to save my photo to gallery with these text elements added by me .But my code only saving the image not the text elements . So help me to get rid of this .
My code as bellow :
class ImageSaver : NSObject {
var successHandler: (() -> Void)?
var errorHandler: ((Error) -> Void)?
@ObservedObject var model : TextBoxModel = TextBoxModel()
@Published var rect : CGRect = .zero
func writeToPhotoAlbum(imageData : Data){
let SwiftUIView = ZStack{
ForEach(model.textBoxes){box in
ZStack {
Text(box.text)
.font(.custom(box.textFont,size : CGFloat(box.textSize)))
.foregroundColor(box.textColor)
.padding(box.bgPadding)
.background(
ZStack {
RoundedRectangle(cornerRadius: box.bgRadius)
.fill(box.bgColor.opacity(box.bgSize))
RoundedRectangle(cornerRadius: 5)
.stroke(Color.black,style : StrokeStyle(
lineWidth : 1, lineCap : .round , dash : [5]
))
}
)
.opacity(box.textOpacity)
.shadow(color: box.shadowColor, radius: box.shadowSize)
.rotationEffect(box.rotationAngle)
}
.offset(box.offset)
}
}
.frame(width: UIScreen.main
.bounds.width, height: UIScreen.main
.bounds.width)
let controller = UIHostingController(rootView: SwiftUIView).view!
controller.frame = rect
controller.backgroundColor = .clear
controller.drawHierarchy(in: CGRect(origin: .zero, size: rect.size), afterScreenUpdates: true)
if let image = UIImage(data: imageData),let cgImage = image.cgImage?.cropping(to: image.cropRect()){
guard let pngData = UIImage(cgImage: cgImage).pngData() else { return }
guard let finalImage = UIImage(data: pngData) else { return }
UIImageWriteToSavedPhotosAlbum(finalImage, self, #selector(saveError), nil)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
