Android - 从图库中选择图像,然后调整其大小以适合ImageView

时间:2015-12-20 02:56:22

标签: android-imageview

我试图将图像放入ImageView以保持纵横比,它会加载图像,但我不知道如何调整它的大小。如果图像太大我想裁剪它,如果它很小我想要适合ImageView,我的代码到目前为止它是这样的:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();
            ImageView imgView = (ImageView) findViewById(R.id.imageButtonFotoPerfil);
            // Set the Image in ImageView after decoding the String
            imgView.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

和imageView的XML:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButtonFotoPerfil"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="15dp"
    android:onClick="loadImagefromGallery"
    android:src="@drawable/perfil_persona_b"
    android:background="@null"/>

1 个答案:

答案 0 :(得分:1)

layout_widthhegiht更改为100dp120dp您想要的尺寸,或者您可以根据屏幕尺寸计算图像尺寸。