zero

(Bitmap) view?

A screenshot of a View is a simple way to convert a View into a Bitmap. There are two ways to do this.

1.1 drawingcache

We’ll just talk about how it works, what it is and why it’s interesting to learn one.

private static Bitmap viewToBitmap(View v) {
    v.setDrawingCacheEnabled(true);
    v.buildDrawingCache();
    Bitmap screenshot = v.getDrawingCache();
    v.setDrawingCacheEnabled(false);
    return screenshot;
}
Copy the code

Simply get the view’s DrawingCache and close it (setDrawingCacheEnabled(false)). Note, however, that this method requires that the view is already displayed on the screen through a Layout.

1.2 canvas to draw

This idea is direct, first look at the code:

private static Bitmap viewToBitmap(View v) {
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        v.draw(canvas);
        return screenshot;
    }
Copy the code

Create a bitmap that is the same width and height as view. ARGB_4444 refers to the pixel type of the bitmap.

ARGB_8888: The four channels are 8 bits, each pixel occupies 4 bytes, the picture quality is the highest, but the memory usage is also the largest; ARGB_4444: All four channels are 4 bits, each pixel occupies 2 bytes, and the image is very distorted; RGB_565: No A channel, each pixel occupies 2 bytes, image distortion is small, but no transparency; ALPHA_8: Only A channel, each pixel occupies A large size of 1 byte, only transparency, no color value.

Then you create the canvas and draw it using the view.draw () method.

// As a beginner in Android development, if I have any mistakes or shortcomings, please point them out. I hope to make progress together with you.