Screenshot in Swift iOS

Get screenshot of current screen in iOS/swift for sharing

// to create an image from screenshot

UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

// to share the image

var imagesToShare = [AnyObject]()
imagesToShare.append(image)

let activityViewController = UIActivityViewController(activityItems: imagesToShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
presentViewController(activityViewController, animated: true, completion: nil)

Save a screenshot as pdf or high resolution-image using Swift 5 xcode 13

Just convert your image to pdf via PDFKit

import PDFKit
let pdfPage = PDFPage(image: screenshotImage)
let fm = FileManager.default urls = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let savedPDF = urls!.appendingPathComponent("pdfPage.pdf") pdfPage?.document?.write(toFile: "pdfPage")

Trying to make a screenshot button that sends the screenshot to my camera roll, when the button is clicked. Swift 3, Xcode 8, IOS

The problem is you have put screenshot taking code inside nested function of your buttonAction method name captureScreen and never called that method, there is no need to add nested method. So simply remove that function and put the screenshot code directly inside the button action method. So replace your button action with this one.

@IBAction func buttonAction(_ sender: UIButton) {

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}

How do I get a screenshot when my app working background in swift?

It is not possible. Apple allows only few process types in the background, and screenshot isn't one of them.

How to take screenshot of a UIView in swift?

For drawing of one view, just use this:

    // Begin context
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)

// Draw view in that context
drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

If you want to use it multiple times, probably extension would do the job:

//Swift4

extension UIView {

func takeScreenshot() -> UIImage {

// Begin context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)

// Draw view in that context
drawHierarchy(in: self.bounds, afterScreenUpdates: true)

// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

if (image != nil)
{
return image!
}
return UIImage()
}
}

//Old Swift

extension UIView {

func takeScreenshot() -> UIImage {

// Begin context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale)

// Draw view in that context
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return image
}
}

To explain what those parameters do:

UIGraphicsBeginImageContextWithOptions() creates a temporary rendering
context into which the original is drawn. The first argument, size, is
the target size of the scaled image. The second argument, isOpaque is
used to determine whether an alpha channel is rendered. Setting this
to false for images without transparency (i.e. an alpha channel) may
result in an image with a pink hue. The third argument scale is the
display scale factor. When set to 0.0, the scale factor of the main
screen is used, which for Retina displays is 2.0 or higher (3.0 on the
iPhone 6 Plus).

More about it here http://nshipster.com/image-resizing/

As for the draw call, Apple Docs explains it to detail here and here

Screenshot on swift programmatically

If you have some sort of Objective-C knowledge then here is the answer that you want.

Open this Link and follow the last answer which iterates through all the view hierarchy and And have line by line comments to fully understand the code.

The Image is finally converted into both NSData and UIImage.
If you are still confuse then i can convert it into swift but first try it by your self.

Here is the Swift code of that Answer.

func screenshot() -> UIImage {
let imageSize = UIScreen.main.bounds.size as CGSize;
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
let context = UIGraphicsGetCurrentContext()
for obj : AnyObject in UIApplication.shared.windows {
if let window = obj as? UIWindow {
if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
// so we must first apply the layer's geometry to the graphics context
context!.saveGState();
// Center the context around the window's anchor point
context!.translateBy(x: window.center.x, y: window.center
.y);
// Apply the window's transform about the anchor point
context!.concatenate(window.transform);
// Offset by the portion of the bounds left of and above the anchor point
context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x,
y: -window.bounds.size.height * window.layer.anchorPoint.y);

// Render the layer hierarchy to the current context
window.layer.render(in: context!)

// Restore the context
context!.restoreGState();
}
}
}
let image = UIGraphicsGetImageFromCurrentImageContext();
return image!
}

Screenshot in Swift iOS?

With Swift 4 / iOS 10.3, you can choose one of the following ways in order to solve your problem.



1. Take a screenshot of a view controller's view

The following code shows how to take a screenshot and save it in the device photo album:

import UIKit

class ViewController: UIViewController {

/* ... */

@IBAction func screenshot(_ sender: UIBarButtonItem) {
//Create the UIImage
UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else { return }
view.layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()

//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

}

Note that the result of this code will be a .JPG image. Also note that the navigation bar and the status bar will not appear in the final image.

Since iOS 10, as an alternative to the previous code, you can use the code below:

import UIKit

class ViewController: UIViewController {

/* ... */

@IBAction func screenshot(_ sender: UIBarButtonItem) {
//Create the UIImage
let renderer = UIGraphicsImageRenderer(size: view.frame.size)
let image = renderer.image(actions: { context in
view.layer.render(in: context.cgContext)
})

//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

}


2. Take a screenshot of an iPhone window

If you want to take a screenshot that includes the navigation bar (but not the status bar), you can use the following code:

import UIKit

class ViewController: UIViewController {

/* ... */

@IBAction func screenshot(_ sender: UIBarButtonItem) {
//Create the UIImage
guard let layer = UIApplication.shared.keyWindow?.layer else { return }
UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else { return }
layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()

//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

}

Since iOS 10, as an alternative to the previous code, you can use the code below:

import UIKit

class ViewController: UIViewController {

/* ... */

@IBAction func screenshot(_ sender: UIBarButtonItem) {
//Create the UIImage
guard let layer = UIApplication.shared.keyWindow?.layer else { return }
let renderer = UIGraphicsImageRenderer(size: layer.frame.size)
let image = renderer.image(actions: { context in
layer.render(in: context.cgContext)
})

//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

}


Reminder

Since iOS 10, in order to prevent your app from crashing when calling your screenshot(_:) method, you need to add the key NSPhotoLibraryUsageDescription to your project's Info.plist file:

NSPhotoLibraryUsageDescription
Some description to explain why access is required


Related Topics



Leave a reply



Submit