Swift에서 전체 화면 스크린 샷을 찍으려면 어떻게하나요?
이 코드를 찾았습니다 .
func screenShotMethod() {
//Create the UIImage
UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
탐색 표시 줄과 같은 다른 모든 요소를 스크린 샷으로 가져 오려면 어떻게해야합니까?
답을 던지는 대신 현재 코드의 기능과 전체 화면을 캡처하도록 수정하는 방법을 설명하겠습니다.
UIGraphicsBeginImageContext(view.frame.size)
이 코드 줄은와 동일한 크기의 새 이미지 컨텍스트를 만듭니다 view
. 여기에 데려 갈 수있는 중요한 것은 새 이미지 컨텍스트는 점이다 과 같은 크기view
. 저해상도 (레티 나가 아닌) 버전의 애플리케이션을 캡처하려는 경우가 아니라면 UIGraphicsBeginImageContextWithOptions
대신 사용해야 합니다. 그런 다음 통과 0.0
하여 장치 기본 화면과 동일한 배율을 얻을 수 있습니다.
view.layer.renderInContext(UIGraphicsGetCurrentContext())
이 코드 줄은 뷰의 레이어를 현재 그래픽 컨텍스트 (방금 생성 한 컨텍스트)로 렌더링합니다. 여기서 제거해야 할 가장 중요한 것은 view
이미지 컨텍스트 로만 (및 하위 뷰) 만 그려진다는 것입니다.
let image = UIGraphicsGetImageFromCurrentImageContext()
이 코드 줄은 그래픽 컨텍스트에 그려진 것에서 UIImage 개체를 만듭니다.
UIGraphicsEndImageContext()
이 코드 줄은 이미지 컨텍스트를 종료합니다. 정리되었습니다 (컨텍스트를 생성했으며 제거해야합니다.
그 결과 view
,와 같은 크기의 이미지 view
와 해당 하위 뷰가 그려집니다.
모든 것을 이미지에 그리려면 화면 크기의 이미지를 만들고 화면에있는 모든 것을 그 안에 그려야합니다. 실제로는 응용 프로그램의 "키 창"에있는 모든 것에 대해 이야기하고있을 것입니다. UIWindow
의 서브 클래스 이므로 UIView
이미지 컨텍스트로도 그릴 수 있습니다.
스위프트 4
/// Takes the screenshot of the screen and returns the corresponding image
///
/// - Parameter shouldSave: Boolean flag asking if the image needs to be saved to user's photo library. Default set to 'true'
/// - Returns: (Optional)image captured as a screenshot
open func takeScreenshot(_ shouldSave: Bool = true) -> UIImage? {
var screenshotImage :UIImage?
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
guard let context = UIGraphicsGetCurrentContext() else {return nil}
layer.render(in:context)
screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = screenshotImage, shouldSave {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
return screenshotImage
}
Swift 2 업데이트
이 코드는 작동을 제공하지만 당신은 캡처 할 수 없습니다 NavigationBar
와를 StatusBar
스크린 샷에. 를 포함 할 기기의 스크린 샷을 찍으려면 NavigationBar
다음 코드를 사용해야합니다.
func screenShotMethod() {
let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)
}
이 코드로 :
- 앱을 처음 실행하고이 메서드를 호출하면 iOS 기기가 카메라 롤에 이미지를 저장할 수있는 권한을 요청합니다.
- 이 코드의 결과는 .JPG 이미지입니다.
- 은
StatusBar
최종 이미지에 나타나지 않습니다.
세부
- Xcode 9.3, Swift 4.1
- Xcode 10.2 (10E125) 및 11.0 (11A420a), Swift 5
iOS에서 테스트 : 9, 10, 11, 12
해결책
import UIKit
extension UIApplication { func makeSnapshot() -> UIImage? { return keyWindow?.layer.makeSnapshot() } }
extension CALayer {
func makeSnapshot() -> UIImage? {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
return screenshot
}
}
extension UIView {
func makeSnapshot() -> UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) }
} else {
return layer.makeSnapshot()
}
}
}
extension UIImage {
convenience init?(snapshotOf view: UIView) {
guard let image = view.makeSnapshot(), let cgImage = image.cgImage else { return nil }
self.init(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation)
}
}
용법
imageView.image = UIApplication.shared.makeSnapshot()
// or
imageView.image = view.makeSnapshot()
// or
imageView.image = view.layer.makeSnapshot()
// or
imageView.image = UIImage(snapshotOf: view)
오래된 솔루션
Xcode 8.2.1, 스위프트 3
iOS 10x 용 버전 1
import UIKit
extension UIApplication {
var screenShot: UIImage? {
if let layer = keyWindow?.layer {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
}
return nil
}
}
iOS 9x, 10x 용 버전 2
iOS 9x에서 버전 1 코드 를 사용하려고하면 오류가 발생합니다. CGImageCreateWithImageProvider : invalid image provider : NULL.
import UIKit
extension UIApplication {
var screenShot: UIImage? {
if let rootViewController = keyWindow?.rootViewController {
let scale = UIScreen.main.scale
let bounds = rootViewController.view.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale);
if let _ = UIGraphicsGetCurrentContext() {
rootViewController.view.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
}
return nil
}
}
용법
let screenShot = UIApplication.shared.screenShot!
Swift 3 예제 :
func captureScreen() -> UIImage? {
guard let context = UIGraphicsGetCurrentContext() else { return .none }
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
쉽게 나는 그것의 파일에 확장자를 추가 할 것입니다
import UIKit
public extension UIWindow {
func capture() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.frame.size, self.opaque, UIScreen.mainScreen().scale)
self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
다음과 같이 내선 번호를 호출하십시오 ...
let window: UIWindow! = UIApplication.sharedApplication().keyWindow
let windowImage = window.capture()
마찬가지로 UIView를 확장하여 그 이미지를 캡처 할 수 있습니다 ....
iOS 10에서 컨텍스트를 만드는 데 권장되는 방법은 UIGraphicsImageRenderer
.
extension UIView {
func capture() -> UIImage? {
var image: UIImage?
if #available(iOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.opaque = isOpaque
let renderer = UIGraphicsImageRenderer(size: frame.size, format: format)
image = renderer.image { context in
drawHierarchy(in: frame, afterScreenUpdates: true)
}
} else {
UIGraphicsBeginImageContextWithOptions(frame.size, isOpaque, UIScreen.main.scale)
drawHierarchy(in: frame, afterScreenUpdates: true)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return image
}
}
이 방법을 사용합니다.
func captureScreen() -> UIImage {
var window: UIWindow? = UIApplication.sharedApplication().keyWindow
window = UIApplication.sharedApplication().windows[0] as? UIWindow
UIGraphicsBeginImageContextWithOptions(window!.frame.size, window!.opaque, 0.0)
window!.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image;
}
상태 표시 줄을 제외한 모든 것을 캡처하며 카메라 롤에 이미지를 저장할 권한을 요청하지 않습니다.
도움이 되었기를 바랍니다.
// Full Screen Shot function. Hope this will work well in swift.
func screenShot() -> UIImage {
UIGraphicsBeginImageContext(CGSizeMake(frame.size.width, frame.size.height))
var context:CGContextRef = UIGraphicsGetCurrentContext()
self.view?.drawViewHierarchyInRect(frame, afterScreenUpdates: true)
var screenShot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return screenShot
}
UIWindow 용 Swift 3 확장
public extension UIWindow {
func capture() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}]
This is similar, hopefully it helps someone in the future.
self.view.image() //returns UIImage
Here's a Swift 3 solution
https://gist.github.com/nitrag/b3117a4b6b8e89fdbc12b98029cf98f8
view.snapshotView(afterScreenUpdates: true)
My version also capture a keyboard. Swift 4.2
extension UIApplication {
var screenshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
for window in windows {
window.layer.render(in: context)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Swift 4 or above.
For extension and call by UIView that you capture.
Declaration
extension UIView {
func viewCapture() -> UIImage? {
UIGraphicsBeginImageContext(self.frame.size)
guard let cgContext = UIGraphicsGetCurrentContext() else {
print("Fail to get CGContext")
return nil
}
self.layer.render(in: cgContext)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
print("Fail to get Image from current image context")
return nil
}
UIGraphicsEndImageContext()
return image
}
}
Usage
var m_image = UIImage()
if let tempCaptureImg = self.m_Capture_View.viewCapture() {
viewController.m_image = tempCaptureImg
}
// m_Capture_View is type of UIView
This is how I do it in Swift 4
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.render(in: UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
now screenshot will be type UIImage
참고URL : https://stackoverflow.com/questions/25448879/how-do-i-take-a-full-screen-screenshot-in-swift
'Program Tip' 카테고리의 다른 글
Grails 2.0에서 Grails 구성에 액세스하는 방법은 무엇입니까? (0) | 2020.11.22 |
---|---|
선택한 Jquery 플러그인-선택한 값 가져 오기 (0) | 2020.11.22 |
C ++ 참조가 참조하는 변수를 어떻게 변경할 수 있습니까? (0) | 2020.11.22 |
Groovy 내장 REST / HTTP 클라이언트? (0) | 2020.11.22 |
ASP.NET에서 현재 도메인 이름을 얻는 방법 (0) | 2020.11.22 |