简体   繁体   English

将视图转换为位图

[英]Convert view to bitmap

I have a view I want to create a bitmap for that view(later I want to print that bitmap). 我有一个视图,我想为该视图创建一个位图(后来我想打印该位图)。 What I have tried is as follows 我尝试过如下

private Bitmap convertViewToBitMap() {      
    View v = rootView;   //rootView is my view to be converted in bitmap
    v.setDrawingCacheEnabled(true);
    Bitmap b = v.getDrawingCache();
    return b;
}

My view "rootview" is a expandable list, when I call convertViewToBitMap() , I get the bitmap of view which is visible on screen, but if view is expanded, the expanded part which is going out of screen does not come in bitmap. 我的视图“ rootview”是一个可扩展的列表,当我调用convertViewToBitMap() ,我得到了在屏幕上可见的视图位图,但是如果视图被扩展,则离开屏幕的扩展部分不会出现在位图中。 So is there a way to get a bitmap of complete view even if it is partially visible on screen? 那么,即使在屏幕上部分可见,有没有办法获得完整视图的位图?

Try this: 尝试这个:

  1. Make some adjustments to your view. 对您的视图进行一些调整。 "Measure" method defines the proper dimensions of your view (change 1000 and 600 to what suits you best) “度量”方法定义了视图的正确尺寸(将1000和600更改为最适合您的视图)

     view.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(600, MeasureSpec.EXACTLY)); 
  2. Re-define your view with the new measurements (change also 0,0) 用新的测量重新定义您的视图(也更改为0,0)

      view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
  3. Create the bitmap 创建位图

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

After that, you can draw your bitmap to any view 之后,您可以将位图绘制到任何视图

               Canvas cn=new Canvas(bm); 
               anyview.draw(cn);

Also, you can save the bitmap into a file 另外,您可以将位图保存到文件中

           try {
                    FileOutputStream out = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, out);

                    out.flush();
                    out.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM