Rendering a UIImage of a UIHostingController results in a offset/clipped image

Originator:jonas.bromo
Number:rdar://FB9648456 Date Originated:Sep 23, 2021
Status:Open Resolved:
Product:SwiftUI Product Version:iOS 15
Classification:Incorrect behavior Reproducible:Always
 
When creating a UIImage from a SwiftUI View, using a UIHostingController and a UIGraphicsImageRenderer, the resulting image is offset/clipped.
The issue started appearing when building with Xcode 13.0 (13A233) after having worked previously when using Xcode 12.5.1.
See the attached SnapshotBug.swift consistently showing the problem.
The offset/clipping also seems to be device orientation dependent...

Reproducible in Xcode 13.0 (13A233), iOS App, iPhone 13 Pro iOS 15.0 Simulator.

SnapshotBug.swift
```swift
import SwiftUI
import UIKit

struct SnapshotBug: View {

    @State var renderedImage: UIImage?

    var icon: some View {
        Image(systemName: "gear")
            .resizable()
            .scaledToFit()
            .frame(width: 40, height: 40)
    }

    var body: some View {
        VStack(spacing: 20) {
            icon
                .border(.red)
            if let renderedImage = renderedImage {
                Image(uiImage: renderedImage)
                    .border(.red)
            } else {
                Text("An identical image should appear here")
            }
            Button("Render image") {
                renderedImage = icon.toUIImage()
            }
        }
    }

}

extension View {
    func toUIImage() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view!
        view.bounds = CGRect(origin: .zero, size: view.intrinsicContentSize)
        view.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
        let image = renderer.image { _ in
            view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        }
        return image
    }
}
```

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!