In my project, user is choosing an image from gallery which is then set as background of my custom View. And I need the size of that View to be adjusted to the size of the image.
In current version, the size of my custom View is static. But I need it to adjust to the size of the chosen image. And also, I don't know how to set that image as background without it being stretched.
XML file of fragment
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9">
<com.example.kreslenie.mapakreslenie.CanvasMap
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="@+id/mapping_canvas" />
...
</RelativeLayout>
Fragment method which loads the image and then sets it as background
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == -1 && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = Bitmap.createBitmap(BitmapFactory.decodeFile(imgDecodableString));
Drawable image = new BitmapDrawable(activity.getResources(), bitmap);
canvas.setBackground(image);
} else {
Toast.makeText(activity, "You haven't picked any Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(activity, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}