
まず、サンプルコードです。
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(){
//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()!
//画面の内容をContextに書き込む
self.view.layer.render(in: context)
//UIImageを取得
let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
//Contextを閉じる
UIGraphicsEndImageContext()
imageView1.image = capturedImage
}
}
まずはUIGraphicsBeginImageContextWithOptionsを使用して、画面をキャプチャした内容を保存するBitmap画像のContextを設定します。
その後、取得したContextに画面の内容を書き込みます。
(上記サンプルの「self.view.layer.render(in: context)」)
その後、UIGraphicsGetImageFromCurrentImageContextを使用して、ContextからUIImageを取得します。
最後にUIGraphicsEndImageContext()を宣言してContextを閉じます。
Write a comment