[iOS]How to capture screen

[日本語]

 

I introduce how to capture screen and make a bitmap image on iOS this time.

 

Environment:Xcode 8.3, Swift 3

 

Sample code is below.

import UIKit

 

class ViewController: UIViewController {

  let label1:UILabel = UILabel()

  let imageView1:UIImageView = UIImageView()

  let button1:UIButton = UIButton()

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    label1.frame = CGRect(x: 10, y: 20, width: 100, height: 100)

    label1.text = "Label1"

    label1.backgroundColor = UIColor.blue

    self.view.addSubview(label1)

 

    imageView1.frame = CGRect(x: 10, y: 125, width: 300, height: 300)

    imageView1.layer.borderWidth = 0.5

    imageView1.contentMode = .scaleAspectFit

    self.view.addSubview(imageView1)

 

    button1.frame = CGRect(x: 10, y: 430, width: 100, height: 50)

    button1.backgroundColor = UIColor.blue

    button1.layer.cornerRadius = 5

    button1.setTitle("Button1", for: .normal)

    button1.addTarget(self, action: #selector(self.touchUpButton1), for: .touchUpInside)

    self.view.addSubview(button1)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

 

  func touchUpButton1(){

    //Get context

    let rect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    let context: CGContext = UIGraphicsGetCurrentContext()!

 

    //Write screen's objects' info at context

    self.view.layer.render(in: context)

 

    //Get UIImage

    let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!

 

    //Close context

    UIGraphicsEndImageContext()

    imageView1.image = capturedImage

  }

}

At first, use UIGraphicsBeginImageContextWithOptions, and make context of bitmap for capturing screen.

And write screen's objects' info at context.("self.view.layer.render(in:context)")

 

And use UIGraphicsGetImageFromCurrentImageContext, and get UIImage from context.

At last, use UIGraphicsEndImageContext, and close context.