更改方向时,ImageView裁剪图像消失

时间:2015-09-30 07:00:12

标签: android android-studio imageview orientation

我有一个活动,我拍照,裁剪图像,然后显示裁剪的图像。这是我的代码。

public class MainActivity extends Activity {
    private static final int TakePicture = 1;
    ImageView imgview;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgview = (ImageView) findViewById(R.id.imageView1);
        Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
        buttonCamera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // call android default camera
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
                // ******** code for crop image
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 0);
                intent.putExtra("aspectY", 0);
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 150);
                try {
                    intent.putExtra("return-data", true);
                    startActivityForResult(intent, TakePicture);
                } catch (ActivityNotFoundException e) {
                    // Do nothing for now
                }
            }
        });
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                imgview.setImageBitmap(photo);
            }
    }

}

当我将方向从纵向更改为横向时,位图中设置的图像将消失。有没有办法保存图像的当前状态,即使方向从横向更改为纵向,反之亦然。?

2 个答案:

答案 0 :(得分:0)

我添加了保存应用当前状态的方法..

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    image = savedInstanceState.getParcelable("BitmapImage");
    this.photo = image;
    imageView.setImageBitmap(photo);
    super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState (Bundle savedInstanceState) {
    savedInstanceState.putParcelable("BitmapImage", photo);
    super.onSaveInstanceState(savedInstanceState);
}

我希望这会有所帮助..

答案 1 :(得分:-1)

您没有可以保存应用当前状态的方法。使用onSaveInstanceState进行保存。您可以在此处找到有关活动和保存值的所有信息:http://developer.android.com/reference/android/app/Activity.html

亲切的问候