Android Convert view to BitMap

2020-03-30 06:39发布

问题:

I'm trying to convert a view to bitmap but I lose the black color. I'm converting like this:

Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);

Example

How can i convert to bitmap so the black of the percentage value is not lost?

Thanks, Regards

回答1:

Hi you can use this method to convert View to Bitmap

private Bitmap createBitmapFromView(Context context, View view) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }


回答2:

If you want to get result as you see in your view , must use below code.

private static Bitmap getBitmapFromView(Context ctx, View view) {
        view.setLayoutParams(new 
ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, 
ConstraintLayout.LayoutParams.MATCH_PARENT));
        DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
            view.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels,
                View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(dm.heightPixels,
                    View.MeasureSpec.EXACTLY));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), 
view.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
        view.draw(canvas);
        return bitmap;
    }

Note: Your view must have background color.