将帧布局保存为位图及其子视图,但imageView(subView)提供黑屏

时间:2016-05-02 10:54:45

标签: android view bitmap

我有一个framelayout。 它包括一个按钮。 在运行时,我单击按钮从图库中选择一个图像。

我创建了一个imageView,从imageView上的库中设置所选图像,并将imageView添加到framelayout。

然后我将整个视图(framelayout)保存为位图。 但是保存的位图只显示按钮和imageView应该是的黑屏。

我尝试了很多方法,但无法解决它......

请帮助

public class MainActivity extends AppCompatActivity {

Button b;
RelativeLayout frame;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button) findViewById(R.id.b);
    frame = (RelativeLayout) findViewById(R.id.frame);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, 1);
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case 1 :
            Uri selectedImage = data.getData();
              try {
                bitmap = MediaStore.Images.Media.getBitmap(
                        MainActivity.this.getContentResolver(), selectedImage);
            } catch (IOException e) {
                e.printStackTrace();
            }





            ImageView i = new ImageView(MainActivity.this);
            i.setImageBitmap(bitmap);

            frame.addView(i);
            frame.invalidate();


           Bitmap bitmapFromView = Bitmap.createBitmap(frame.getWidth(),frame.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvass = new Canvas(bitmapFromView);
            frame.draw(canvass);
            saveBitmap(bitmapFromView);


            break;
    }

}


public void saveBitmap(Bitmap bitmap) {
    File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }

    MediaScannerConnection.scanFile(getApplicationContext(),
            new String[]{imagePath.getAbsolutePath()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    // TODO Auto-generated method stub

                }
            });
}




 /*
 also tried this...not working

public static Bitmap loadBitmapFromView(View v) {
    Bitmap bitmap;
    v.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    return bitmap;
   }

    */

}

2 个答案:

答案 0 :(得分:0)

现在终于我在我测试过的大部分设备上制作了代码

1)MainActivity.class

public class MainActivity extends AppCompatActivity {

    private final int SELECT_PHOTO = 2;
    private ImageView contactimage;
    private LinearLayout content;
    private TextView textall;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        content = (LinearLayout) findViewById(R.id.frame_save);


        contactimage = (ImageView) findViewById(R.id.contactimage);

        textall = (TextView) findViewById(R.id.textall);

        textall.setText("MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "         MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "          MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "           MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "            MY TEst MY TEst MY TEst MY TEst MY TEst");


        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    }


    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {

                    try {
                        final Uri imageUri = data.getData();
                        final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        contactimage.setImageBitmap(selectedImage);

                        try {
                            content.setDrawingCacheEnabled(true);

                            content.setDrawingCacheEnabled(true);

                            content.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

                            content.layout(0, 0, content.getMeasuredWidth(), content.getMeasuredHeight());

                            content.buildDrawingCache(true);
                            Bitmap bitmap = getBitmapFromView(content);
                            content.setDrawingCacheEnabled(false);

                            File file, f = null;
                            if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                                file = new File(android.os.Environment.getExternalStorageDirectory(), "Handcare");
                                if (!file.exists()) {
                                    file.mkdirs();

                                }
                                f = new File(file.getAbsolutePath() + File.separator + "MyImage.png");
                            }
                            FileOutputStream ostream = new FileOutputStream(f);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
                            ostream.close();


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

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

                }
        }
    }


    private Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return returnedBitmap;
    }
}

2)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity"
    android:background="@android:color/white">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:id="@+id/frame_save">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:id="@+id/textall"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/contactimage"
        android:layout_margin="10dp"/>

   </LinearLayout>
</LinearLayout>

3)在清单中

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

答案 1 :(得分:0)

我做到了。

我在onActivityResult()中添加图像并顺序保存它;

这个:

        ImageView i = new ImageView(MainActivity.this);
        i.setImageBitmap(bitmap);
        frame.addView(i);
        frame.invalidate();

和此:

        Bitmap bitmapFromView =   Bitmap.createBitmap(frame.getWidth(),frame.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvass = new Canvas(bitmapFromView);
        frame.draw(canvass);
        saveBitmap(bitmapFromView);

似乎虽然添加的图像在设备上对我来说是可见的,但是内部的android没有处理它。在此之前可能发生我试图保存视图。

现在我终于通过在onActivityResult()中添加了imageView来解决它; 并在单独的按钮上保存此视图。

当我发出一个工作线程时,我也得到了肯定的结果,这个线程在添加了imageview后会睡1秒钟。 然后在工作线程的postExecute()中,我将视图保存为位图。