Is it possible to take a screenshot of a view, without showing the view?

后端 未结 1 820
故里飘歌
故里飘歌 2020-12-09 12:00

Short question:

Suppose I have some kind of a layout file and I inflate it (or use the normal CTORs in code).

Instead of showing the inflated view, I wish to

1条回答
  •  心在旅途
    2020-12-09 12:31

    OK, I've found a possible way to do it, based on this link :

    public static Bitmap drawToBitmap(Context context,final int layoutResId,
                                      final int width,final int height)
    {
        final Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bmp);
        final LayoutInflater inflater =
             (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View layout = inflater.inflate(layoutResId,null);
        layout.setDrawingCacheEnabled(true);
        layout.measure(
             MeasureSpec.makeMeasureSpec(canvas.getWidth(),MeasureSpec.EXACTLY),
             MeasureSpec.makeMeasureSpec(canvas.getHeight(),MeasureSpec.EXACTLY));
        layout.layout(0,0,layout.getMeasuredWidth(),layout.getMeasuredHeight());
        canvas.drawBitmap(layout.getDrawingCache(),0,0,new Paint());
        return bmp;
    }
    

    Example of usage:

    public class MainActivity extends ActionBarActivity
    {
        @Override
        protected void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            final ImageView iv = (ImageView)findViewById(R.id.image);
            final DisplayMetrics metrics = getResources().getDisplayMetrics();
            final Bitmap b = drawToBitmap(this,R.layout.test, metrics.widthPixels,
                                        metrics.heightPixels);
            iv.setImageBitmap(b);
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题