[Android] view.getDrawingCache()がDeprecatedになったのでPixelCopyでスクリーンキャプチャを撮る

Viewのスクリーンキャプチャを撮ると行ったらgetDrawingCache()だよね!

APILevel1からある便利なやつ!昔流行った?無音カメラとかこれで撮影してたんだよね?多分だけど。

Viewのスクリーンキャプチャ撮る必要があったから久しぶりに使ったら・・・・

取り消し線たくさん\(^o^)/

公式見ると


This method was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.


このメソッドはAPIレベル28で廃止されました。 ハードウェアアクセラレーションを使用すると、中間キャッシュレイヤはほとんど不要になり、作成および更新のコストが原因でパフォーマンスが大幅に低下する可能性があります。層。アルファアニメーションなどキャッシングレイヤが便利な場合は、setLayerType(int、android.graphics.Paint)がハードウェアレンダリングでこれを処理します。ビュー階層のごく一部または個々のビューのソフトウェアレンダリングされたスナップショットの場合は、ビットマップまたは画像からキャンバスを作成し、ビュー上でdraw(android.graphics.Canvas)を呼び出すことをお勧めします。ただし、これらのソフトウェアレンダリングの使用は推奨されず、Config.HARDWAREビットマップ、リアルタイムシャドウ、およびアウトラインクリッピングなどのハードウェアのみのレンダリング機能との互換性の問題があります。フィードバックレポートまたは単体テスト用のUIのスクリーンショットについては、PixelCopy APIをお勧めします。

だってさ。超最近Deprecatedになった模様。

スポンサーリンク

代替方法

ってことで代替方法。StackOverFlow先生が教えてくれた。

PixelCopyを使ってViewのスクリーンキャプチャを撮る。

fun getBitmapFromView(view: View, callback: (Bitmap?) -> Unit) {
   window?.let { window ->
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val locationOfViewInWindow = IntArray(2)
        view.getLocationInWindow(locationOfViewInWindow)
        try {
            PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
                if (copyResult == PixelCopy.SUCCESS) {
                    callback.invoke(bitmap)
                } else {
                    callback.invoke(null)
                }
            }, Handler())
        } catch (e: IllegalArgumentException) {
            callback.invoke(null)
        }
    }
}

PixelCopy.request()がAPILevel28からしかないみたいだけど、これでスクリーンキャプチャ撮れる

タイトルとURLをコピーしました