Two ways to convert View to Bitmap

Method 1.buildDrawingCache (not recommended)

android.view.View#buildDrawingCache(boolean)

android.view.View#getDrawingCache(boolean)

These two methods are used together to convert View to Bitmap

shortcoming

1. The efficiency is poor. From the source code comments, we can see that the use of this method will affect the rendering performance of View, especially when hardware acceleration is turned on, the software will still be forced to draw once.

2. Although it has scaling parameters, it still draws as a whole, which has poor efficiency and consumes memory

3. When the View is too large, it is easy to cause freeze.

Method 2. View.draw() recommended

Use View's own draw method, combined with Matrix to draw its whole or part on the Canvas with Bitmap as the drawing board, the code is as follows

/**
 * 高效的获取View的裁剪区
 * @param view 需要处理的View
 * @param crop 裁剪区域
 * @param downscaleFactor 缩放参数
 * @return
 */
public static Bitmap getDownscaledBitmapForView(View view, Rect crop, float downscaleFactor) {
    
    

    View screenView = view;

    int width = (int) (crop.width() * downscaleFactor);
    int height = (int) (crop.height() * downscaleFactor);
    float dx = -crop.left * downscaleFactor;
    float dy = -crop.top * downscaleFactor;

    if (width * height <= 0) {
    
    
        return null;
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);//准备图片
    Canvas canvas = new Canvas(bitmap);//将bitmap作为绘制画布
    Matrix matrix = new Matrix();
    matrix.preScale(downscaleFactor, downscaleFactor);
    matrix.postTranslate(dx, dy);
    canvas.setMatrix(matrix);//设置matrix
    screenView.draw(canvas);//讲View特定的区域绘制到这个canvas(bitmap)上去,
    return bitmap;//得到最新的画布
}

Advantage

1. Draw on demand, crop on demand

2. Requires less memory space

3. Does not affect hardware acceleration and is more efficient

Guess you like

Origin blog.csdn.net/wang382758656/article/details/127628087