Skip to content

Instantly share code, notes, and snippets.

@Arime9
Last active November 16, 2022 08:17
Show Gist options
  • Save Arime9/4ec0ac0e2139f9bf2c40c3ca6eaf1a3c to your computer and use it in GitHub Desktop.
Save Arime9/4ec0ac0e2139f9bf2c40c3ca6eaf1a3c to your computer and use it in GitHub Desktop.
View to UIImage - Swift code
import SwiftUI
extension View {
@MainActor public func screenshot(scale: CGFloat = 1.0) -> UIImage? {
if #available(iOS 16.0, *) {
// ImageRendererの方が処理速度が早く、画像が高精細
let renderer = ImageRenderer(content: self)
renderer.scale = scale
renderer.isOpaque = true
return renderer.uiImage
} else {
let controller = UIHostingController(rootView: self)
let view = controller.view!
let bounds = CGRect(origin: .init(x: .zero, y: adjustY()), size: view.intrinsicContentSize)
view.bounds = bounds
view.backgroundColor = .clear
let format = UIGraphicsImageRendererFormat(for: .init(displayScale: scale))
let image = UIGraphicsImageRenderer(bounds: bounds, format: format).image { _ in
view.drawHierarchy(in: bounds, afterScreenUpdates: true)
}
return image
}
}
/// UIGraphicsImageRendererで画像描画時に発生するY座標軸上のズレを調整するためのポイント
///
/// ポートレート時のみズレる
private func adjustY() -> CGFloat {
switch UIScreen.main.nativeBounds.height {
case 1_136: // 4.0 inch
return 10
case 1_334: // 4.7 inch
return 10
case 2_340: // 5.4 inch
return 25
case 2_208: // 5.5 inch
return 10
case 2_436: // 5.8 inch
return 22
case 1_792: // 6.1 inch
return 24
case 2_532: // 6.1 inch
return 71 / 3 // 23.666666666666667
case 2_688: // 6.5 inch
return 22
case 2_778: // 6.7 inch
return 71 / 3 // 23.666666666666667
default:
return .zero
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment