搬砖日记

搬砖日记

The correct way to take screenshots of Android Views

Screenshots#

Method 1:


//Method 1
    fun takePic(view: View, width: Float, height: Float, scroll: Boolean, config: Bitmap.Config?): Bitmap? {
        var width = width
        var height = height
        if (!view.isDrawingCacheEnabled) {
            //isDrawingCacheEnabled is deprecated
            view.isDrawingCacheEnabled = true
        }
        if (width == 0f) {
            width = Consts.width
        }
        if (height == 0f) {
            height = Consts.height
        }
        val bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), config!!)
        bitmap.eraseColor(Color.WHITE)
        val canvas = Canvas(bitmap)
        var left = view.left
        var top = view.top
        if (scroll) {
            left = view.scrollX
            top = view.scrollY
        }
        val status: Int = canvas.save()
        canvas.translate(-left, -top)
        val scale = width / view.width
        canvas.scale(scale, scale, left, top)
        view.draw(canvas)
        canvas.restoreToCount(status)
        val alphaPaint = Paint()
        alphaPaint.setColor(Color.TRANSPARENT)
        canvas.drawRect(0f, 0f, 1f, height, alphaPaint)
        canvas.drawRect(width - 1f, 0f, width, height, alphaPaint)
        canvas.drawRect(0f, 0f, width, 1f, alphaPaint)
        canvas.drawRect(0f, height - 1f, width, height, alphaPaint)
        canvas.setBitmap(null)
        return bitmap
    }

//Method 2
    fun takePic(v: View, width: Int, height: Int, config: Bitmap.Config?): Bitmap? {
        val bmp = Bitmap.createBitmap(v.width, v.height, config!!)
        val c = Canvas(bmp)
        c.drawColor(Color.WHITE)
        v.draw(c)
        return bmp
    }

//Method 3: I think this is the simplest and most useful method, but there is a big pit here, which I will explain later
    fun takePic(view: View): Bitmap? {
        view.buildDrawingCache()
        return view.drawingCache
    }

//Method 4
    fun takePic(v: View): Bitmap? {
        val bmp = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        c.drawColor(Color.WHITE)
        v.draw(c)
        return bmp
    }

Issue#

The above are all methods for capturing screenshots of views. However, sometimes there is a situation where the screenshot remains the same even after the view has changed. In this case, you need to refresh the view's drawing cache. For example, the big pit mentioned in Method 3 is that you need to call view.destroyDrawingCache() before the next call. Or if you have called the setDrawingCacheEnabled(true) method, you need to call setDrawingCacheEnabled(false) after you finish using it.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.