Hello,
I am trying to use the new SwiftUI method called ImageRenderer to render any SwiftUI view into an image. However, I am encountering an issue when using it with AsyncImage:
AsyncImage(url: URL(string: imageURL)) { phase in
if let sampleImage = phase.image {
sampleImage.onAppear{
Task {
render(content: sampleImage)
}
}
} else if phase.error != nil {
Color.red // Indicates an error.
} else {
Color.blue // Acts as a placeholder.
}
}
@MainActor
private func render(content: some View) {
let renderer = ImageRenderer(content: content)
renderer.scale = 500
if let cgImage = renderer.cgImage {
print("Rendering")
ImageSaver.shared.saveCGImageToDisk(cgImage)
}
}
public func saveCGImageToDisk(_ cgImage: CGImage) {
let image = UIImage(cgImage: cgImage, scale: 500, orientation: .down)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}) { success, error in
if success {
print("Image saved to photo library")
} else {
print("Error saving image: \(error?.localizedDescription ?? "unknown error")")
}
}
}
When rendering a different image, such as Image(systemName: "pencil"), everything works as expected. However, when using AsyncImage, it seems that the rendering process is not working as intended.
Here are some screenshots:
What could be causing this issue when rendering AsyncImages with ImageRenderer, and how can it be resolved? Any insights or suggestions are greatly appreciated.
Thank you in advance.