I have an iOS image to which I have applied scale, offset and rotation to, and then clipped. How can I get a copy of the image (or save a copy) with these effects applied?
import SwiftUI
struct ContentView: View {
var body: some View {
Image("minions")
.resizable()
.scaleEffect(1.5)
.rotationEffect(.degrees(20.0))
.offset(CGSize(width: -75.0, height: -50.0))
.aspectRatio(contentMode: .fill)
.frame(width: 160, height: 160, alignment: .center)
.contentShape(Rectangle())
.clipped()
.border(Color.black)
}
}
I have tried ImageRenderer to export bitmap image data from the view, however I only get a copy of the original image without the effects:
import SwiftUI
struct ContentView: View {
var image1 = Image("minions")
var image2 = Image("empty")
var body: some View {
image1
.resizable()
.scaleEffect(1.5)
.rotationEffect(.degrees(20.0))
.offset(CGSize(width: -75.0, height: -50.0))
.aspectRatio(contentMode: .fill)
.frame(width: 160, height: 160, alignment: .center)
.contentShape(Rectangle())
.clipped()
.border(Color.black)
Button(action: {
let imageRenderer = ImageRenderer(content: image1)
image2 = Image(uiImage: imageRenderer.uiImage!)
}, label: {
Text("Copy Image")
})
image2
}
}
1
The modifiers you added to image1
doesn’t change what “image1
” means. image1
still refers to the original image.
You should pass the whole image1.resizable().scaleEffect(1.5)...
expression, with all those modifiers, into ImageRenderer
. Of course, you’d get a lot of code duplication this way, so to avoid that, assign the image1
expression with all those modifiers to a local variable first.
struct ContentView: View {
var image1 = Image("1")
@State var image2: Image?
var body: some View {
// assign this to a local variable first
let image = image1
.resizable()
.scaleEffect(1.5)
.rotationEffect(.degrees(20.0))
.offset(CGSize(width: -75.0, height: -50.0))
.aspectRatio(contentMode: .fill)
.frame(width: 160, height: 160, alignment: .center)
.contentShape(Rectangle())
.clipped()
.border(Color.black)
// this shows it on the view
image
Button(action: {
// pass the image to the ImageRenderer
let imageRenderer = ImageRenderer(content: image)
image2 = Image(uiImage: imageRenderer.uiImage!)
}, label: {
Text("Copy Image")
})
image2
}
}