4
5

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 5 years have passed since last update.

特定のViewのスクリーンショットを撮る

Last updated at Posted at 2018-12-01

# やりたいこと
特定のViewのBitmapを取得し、ImageViewに表示

実装

ScreenShot.kt
class ScreenShot {

    fun generateScreenShot(): Bitmap {
        // 適当なファイル名
        val filename = context.filesDir.path + System.currentTimeMillis().toString() + ".jpg"
        val output = FileOutputStream(filename)

        view.isDrawingCacheEnabled = true
        view.drawingCacheBackgroundColor = Color.TRANSPARENT
        val saveBitmap = Bitmap.createBitmap(view.drawingCache)  // Bitmap生成
        saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
        output.flush()

        view.isDrawingCacheEnabled = false
        return saveBitmap
    }
}

便利に

Extensionに追加しておくと色んなViewからBitmap取得できて便利です。

ViewEx.kt
    val View.screenShot: Bitmap
        get() {
            val filename = context.filesDir.path + System.currentTimeMillis().toString() + ".jpg"
            val output = FileOutputStream(filename)

            isDrawingCacheEnabled = true
            drawingCacheBackgroundColor = Color.TRANSPARENT
            val saveBitmap = Bitmap.createBitmap(drawingCache)
            saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
            output.flush()
    
            isDrawingCacheEnabled = false
            return saveBitmap
        }

特記事項

  • 対象のViewに重なっていたとしても子で無い場合、Bitmapとして出力されません。
  • 書き込み権限が必要
4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?