0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

スクリーンショットをとってSNSでシェアする方法

Last updated at Posted at 2021-03-11

画面の任意の部分をスクリーンショットして、アクティビティビューからSNSでシェアする方法です。アルバムにも画像を保存できます。

import UIKit

class ViewController: UIViewController {

    //インスタンス作成
    private var snapshot = Snapshot()

    @IBAction func didTapTakButton(_ sender: Any) {

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        //snapshotする画面のサイズを規定
        let size = CGSize(width: width, height: height * 12 / 24)

        //snapshotした画像を載せたアクティビティビューを作成
        let activityVC = snapshot.share(size: size, view: view)

        //アクティビティビューを表示
        present(activityVC, animated: true, completion: nil)
    }

}

class Snapshot {

    private var snapshotImage = UIImage()

    func take(size: CGSize, view: UIView) {

        //bitmapの描画環境を構築し、描画開始
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

        //渡されたviewの切り出し
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)

        //切り出した部分をUIImageとして保存
        snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!

        //描画終了
        UIGraphicsEndImageContext()
    }

    func share(size: CGSize,  view: UIView) -> UIActivityViewController {

        //描画してUIImageを切り出し
        take(size: size, view: view)


        //アクティビティビューに渡すために[Any]型に変換
        let items = [snapshotImage] as [Any]

        //アクティビティビューに載せる
        let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil)

        //アクティビティビューを返す
        return activityVC
    }
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?