LoginSignup
7
8

More than 5 years have passed since last update.

[Swift4] Twitterにスクリーンショットを投稿する方法

Last updated at Posted at 2017-11-09

スクリーンショットの取得

ViewControllerの中に以下の関数を追加

     /**
     * @brief  スクリーンショットを取得する
     * @return UIImage
     */
    func getScreenShot()-> UIImage {
        // キャプチャ範囲を決定
        let width = Int(UIScreen.main.bounds.size.width)  //画面横幅いっぱい
        let height = 100
        let size = CGSize(width: width, height: height)
        // ビットマップ画像のcontextを作成
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        // 対象のview内の描画をcontextに複写する.
        self.view.layer.render(in: context)
        // 現在のcontextのビットマップをUIImageとして取得.
        let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        // contextを閉じる.
        UIGraphicsEndImageContext()
        return capturedImage
    }

Twitterへの投稿

実装手段は主に2通り

UIActivityViewController TwiterKit
実装一瞬。LINEやFacebookにも対応。 アプリ入ってなくてもツイートしてもらえる。
× アプリ入ってないとツイートできない 導入がちょっとだけ手間

ここではUIActivityViewControllerを使う

.pngの場合: UIImagePNGRepresentation()をかませる
.jpegの場合: UIImageJPEGRepresentation()をかませる

// スクリーンショットを取得
let shareImage = UIImagePNGRepresentation(getScreenShot())
// 共有項目
let activityItems: [Any] = [shareImage!, "投稿したいテキストおおおお"]
// 初期化処理
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

// iPad用処理
if UIDevice.current.userInterfaceIdiom == .pad {
    activityVC.popoverPresentationController?.sourceView = self.view
    activityVC.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.size.width / 2.0, y: self.view.bounds.size.height / 2.0, width: 1.0, height: 1.0)
}

// UIActivityViewControllerを表示
self.present(activityVC, animated: true, completion: nil)

参考

スクリーンショットをUIImageに保存する方法

7
8
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
7
8