Simple. Add an extension to view.
Swift
extension View {
func snapshot() - UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
Then use body.snapshot() (assuming you use var body: Some View for your View) to take a UIImage snapshot of the View.
Swift
struct ContentView: View {
var textView: some View {
Text("Hello, SwiftUI")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.clipShape(Capsule())
}
var body: some View {
VStack {
textView
Button("Save to image") {
let image = textView.snapshot()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
}
}
Post
Replies
Boosts
Views
Activity
Hey, man. I have a short list of genre IDs in my open-source app here: https://github.com/adityasaravana/Tuneder/blob/main/Tuneder/GenreSelection.swift, if you want to borrow some of those, and here's a simple script I run when my app launches to collect some genre data.
func search(_ query: String) async {
/// This code fetches the genres and ids of songs that that you enter in searchTerm, useful for adding more genres (See GenreSelection)
do {
let songSearch = try await MCatalog.search(for: query, types: [.songs], limit: 3)
for song in songSearch.songs {
let songDetailed = try await MCatalog.song(id: song.id, fetch: [.genres])
for genre in songDetailed.genres! {
print("⚠️⚠️⚠️⚠️⚠️⚠️ GENRE NAME: \(genre.name), ID: \(genre.id) ⚠️⚠️⚠️⚠️⚠️⚠️")
}
}
} catch {
print("caught at MusicManager.searchQuery")
}
}
.onAppear {
#if DEBUG
/// Finding the IDs of genres to add to GenreSelection.
Task {
await musicManager.search("jazz")
}
#endif
}
UPDATE:
You need to import MusadoraKit for the code above to work; https://github.com/rryam/MusadoraKit
Having this same issue, anyone got a solution?