Search code examples
androidimageviewandroid-imageview

Android ImageView strecthes background


TL;DR: It looks fine when setting a drawable to ImageView (see attachment - top). Replacing it with a Bitmap (setImageBitmap) and setting again to the original (setImageBitmap(null) & setBackgroundResource(R...)) leads to the drawable being stretched (see atachment - bottom).

The ImageView element has a resource image when starting the app and it looks fine and not stretched. If the user puts his sign by using another activity, the ImageView is used to show a small thumbnail of his sign and the ImageView gets overwritten by using setImageBitmap().

The issue occurs, when user saves the draft and all fields get emptied. Emptying includes setImageBitmap(null) and setBackGroundResource(R.drawable.ACTUAL_IMAGE_OF_IMG_VIEW).

After resetting the ImageView (deleting Bitmap and setting actual background), the Background-Image gets stretched (see attached picture):

ImageView - Before & After

Changing the orientation of the device (landscape and portrait) the image is normal again. Also there are grid lines on the background of the image, which absolutely doesn't stem from the ressource image.

Would love to hear the way You would solve this.

Edit - Code:

// Inserting Bitmap
private void insertSignature(){
    ivSign.setImageBitmap(signature);
}
// setting signature -> null and adding icon again as background
private void ResetInputFields(){
    ivSign.setImageBitmap(null);
    ivSign.setBackgroundResource(R.drawable.sign_pen);
    // TRIED ALREADY:
    // ivSign.setBackground(getResources().getDrawable(R.drawable.sign_pen));
}

Solution

  • add to your imageView's XML code

     android:scaleType="fitCenter"
    

    or

     android:scaleType="centerInside"
    

    and it will keep its original ratio