2011-10-21 17 views
3

我想渲染视图到位图并保存位图。 但我需要在屏幕外全部做到这一点。在Android中关闭屏幕渲染视图

我已经试过这样:

LayoutInflater inflater = getLayoutInflater(); 
    View linearview = (View) findViewById(R.id.linearview); 
    linearview = inflater.inflate(R.layout.intro, null); 


Bitmap bm = Bitmap.createBitmap(linearview.getMeasuredWidth(), linearview.getMeasuredHeight(), Bitmap.Config.ARGB_8888);     
Canvas c = new Canvas(bm); 
linearview.layout(0, 0, linearview.getLayoutParams().width, linearview.getLayoutParams().height); 
linearview.draw(c); 

    String extStorageDirectory = Environment.getExternalStorageState().toString(); 
    extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
    OutputStream outStream = null; 
    File file = new File(extStorageDirectory, "screen1.PNG"); 

    try { 
     outStream = new FileOutputStream(file); 
     bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
     outStream.flush(); 
     outStream.close(); 


    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

编辑: 我的应用程序崩溃,因为该视图可是没有任何宽度或高度。 (该措施是试图解决这个问题)

和srry的英语不好。

+1

询问崩溃时,你应该总是张贴您的跟踪 – jqpubliq

+0

做一个服务 –

+0

如何设置一个布局到服务? –

回答

1

的问题是在这里:

linearview = inflater.inflate(R.layout.intro, null); 

您需要通过父布局,因此可以适当地测定。 我知道你不希望视图被附加到布局,但是你可以使用父布局来通过使用这个方法的其他版本来测量,并将false传递给attachToRoot。

public View inflate (int resource, ViewGroup root, boolean attachToRoot) 

从paramenters的正式文档:

:可选视图,使其将所生成的分层结构的父(如果attachToRoot为真),否则简单地一个目的,提供了一个为返回的层次结构的根集的LayoutParams值(如果attachToRoot是假的。)

attachToRoot:无论充气层次结构应附加到根参数?如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。

有疑问时,你总是可以通过应用内容作为父布局:

findViewById(android.R.id.content);