Help us understand the problem. What is going on with this article?

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

 やりたいこと

特定の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として出力されません。
  • 書き込み権限が必要
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away