关于创建位图的空指针

时间:2014-07-19 21:03:14

标签: android bitmap scrollview

我正在尝试截取ScrollView,只需从此处复制+粘贴解决方案:Taking a "screenshot" of a specific layout in Android。不幸的是我得到了一个N​​P @ Bitmap b = Bitmap.createBitmap(u.getDrawingCache());

我的XML是

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollingProfile"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="wrap_content"
    android:background="@drawable/tile_tan_repeat">

    <LinearLayout 
    android:id="@+id/paidLayoutLinearParent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
        <!--......-->
    </LinearLayout>
 </ScrollView>

任何人都有任何关于为什么会这样的想法?我从来没有真正使用过保存这样的文件,所以调试这段代码对我来说是非常陌生的。

谢谢!

编辑:这是我正在使用的代码

  public void onClick(View v) {
    if(v.getId()==R.id.screenshot){//source: https://stackoverflow.com/questions/10650049/taking-a-screenshot-of-a-specific-layout-in-android

        View u = findViewById(R.id.scrollingProfilePaid);
        u.setDrawingCacheEnabled(true);                                                
        ScrollView z = (ScrollView) findViewById(R.id.scrollingProfilePaid);
        int totalHeight = z.getChildAt(0).getHeight();
        int totalWidth = z.getChildAt(0).getWidth();
        u.layout(0, 0, totalWidth, totalHeight);    
        u.buildDrawingCache(true);
        Bitmap b = Bitmap.createBitmap(u.getDrawingCache());             
        u.setDrawingCacheEnabled(false);


        //Save bitmap
        String extr = Environment.getExternalStorageDirectory().toString() +   File.separator + "Folder";
        //String fileName = new SimpleDateFormat("yyyyMMddhhmm'profile.jpg'").format(new Date());
        String fileName = "profile.jpg";
        File myPath = new File(extr, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(myPath);
            b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }       
}

1 个答案:

答案 0 :(得分:0)

将代码放在

scrollview.post(
new Runnable()
    {

        @Override
        public void run()
        {
         //this method will call after scrollview's onDraw method
         // so the view is ready to generarte bitmap at this point 
         //put here  your screen shot code

        }
     });