Android View保存为bitmap

如果想把Android的某个view保存为bitmap,非常简单。

基本流程是,先拿到view的宽高,然后创建一个bitmap和一个canvas,canvas使用bitmap作为buffer。然后,调用view.draw(canvas),把view的内容绘制到canvas上。

方法如下:

public static Bitmap saveViewAsBitmap(View view) {
    
    
    int width = view.getWidth();
    int height = view.getHeight();
    if (width <= 0 || height <= 0) {
    
    
        DebugLog.i(TAG, "size is unknown, maybe wrap_content, will measure");
        int specSize = View.MeasureSpec.makeMeasureSpec(0 /* any */, View.MeasureSpec.UNSPECIFIED);
        view.measure(specSize, specSize);
        width = view.getMeasuredWidth();
        height = view.getMeasuredHeight();
    }
    DebugLog.i(TAG, "view size is w " + width + " h " + height);
    if (width <= 0 || height <= 0) {
    
    
        DebugLog.e(TAG, "invalid size, do nothing, return null");
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    if(view.getRight() <= 0 || view.getBottom() <= 0) {
    
    
        view.layout(0, 0, width, height);
        view.draw(canvas);
    } else {
    
    
        view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
        view.draw(canvas);
    }

    return bitmap;
}

需要注意的是,如果拿不到view的宽高,例如view的layout_widthwrap_content的情况下,可能拿不到,则需要调用View.measure来获得一下。

猜你喜欢

转载自blog.csdn.net/newchenxf/article/details/122992257