iOS Development

ios – Save a SwiftUI Picture with an overlaid sample to Pictures App

Spread the love


I am attempting to avoid wasting a SwiftUI Picture to Pictures App. I created a sample overlay for it. However in consequence, an I’ve a picture with a sample of a unique dimension at Pictures App. Is it attainable to use a sample and save a picture in the identical kind? Or initially show it within the kind by which it will likely be saved.

How do I see it in my app
enter image description here

How do I see it within the Pictures App
enter image description here

My code:

struct ImageWithGridOverlayView: View {
    
    @Binding var picture: UIImage?
    @Binding var patternElementSideSize: CGFloat
    @Binding var didSave: Bool
    
    @Atmosphere(.displayScale) non-public var displayScale
    
    var physique: some View {
        if let picture {
            imageView(picture)
                .overlay {
                    gridView()
                }
                .onChange(of: didSave, { _, _ in
                    save()
                })
        }
    }
    
    @ViewBuilder
    non-public func gridView() -> some View {
        let dimension = CGSize(width: patternElementSideSize, peak: patternElementSideSize)
        let picture = UIImage(useful resource: .grid).resized(to: dimension)
        Picture(uiImage: picture)
            .resizable(resizingMode: .tile)
    }
    
    @ViewBuilder
    non-public func imageView(_ picture: UIImage) -> some View {
        Picture(uiImage: picture)
            .resizable()
            .body(maxWidth: .infinity)
            .scaledToFit()
    }
    
    @MainActor
    non-public func save() {
        guard let uiImage = self.render(scale: displayScale) else { return }
        UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
    }
    
}

fileprivate extension UIImage {
    func resized(to dimension: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(dimension: dimension).picture { _ in
            draw(in: CGRect(origin: .zero, dimension: dimension))
        }
    }
}

fileprivate extension View {
    @MainActor
    func render(scale displayScale: CGFloat = 1.0) -> UIImage? {
        let renderer = ImageRenderer(content material: self)
        renderer.scale = displayScale
        
        return renderer.uiImage
    }
}

I additionally tried to make use of VStack and HStack to create a sample, however the end result was the identical.

Leave a Reply

Your email address will not be published. Required fields are marked *