-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathUIView+Screenshot.swift
More file actions
64 lines (53 loc) · 2.07 KB
/
Copy pathUIView+Screenshot.swift
File metadata and controls
64 lines (53 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
protocol Screenshotable {
@MainActor
func screenshot(quality: CGFloat) -> UIImage?
@MainActor
func screenshot(bounds: CGRect) -> UIImage?
}
extension UIView: Screenshotable {
/// Takes a screenshot of the view with a given quality
/// - Parameters:
/// - quality: CGFloat that represents quality of the screenshot.
/// The expected value is 0 to 1 and is defaulted to 1
/// - Returns: The image that represents the screenshot
func screenshot(
quality: CGFloat = CGFloat(UIConstants.ScreenshotQuality)
) -> UIImage? {
return screenshot(frame.size, offset: nil, quality: quality)
}
/// Takes a screenshot of the view by drawing it's content in the provided bounds.
/// - Parameters:
/// - bounds: The area of the view to snapshot
/// - Returns: The image representing the snapshot of the view in the provided bounds.
func screenshot(bounds: CGRect) -> UIImage? {
let renderer = UIGraphicsImageRenderer(size: bounds.size)
return renderer.image { context in
drawHierarchy(
in: bounds,
afterScreenUpdates: true
)
}
}
/// Takes a screenshot of the view with the given size.
private func screenshot(_ size: CGSize, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
guard 0...1 ~= quality else { return nil }
let targetScale: CGFloat = 1.0
let offset = offset ?? .zero
UIGraphicsBeginImageContextWithOptions(
size,
false,
min(UIScreen.main.scale, targetScale) * quality
)
drawHierarchy(
in: CGRect(origin: offset, size: frame.size),
afterScreenUpdates: false
)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}