Android ImageView ScaleType blog helps you to overcome the problem of deciding which scaleType to use with ImageView to fit image inside it.
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
ImageView widget comes with 8 types of scale type you can use, They are as follows:
- center
- centerInside
- centerCrop
- fitXY
- fitCenter
- fitStart
- fitEnd
- matrix
In following example we will look at scaling an image we grabbed from unsplash.com
1. center
Centers the image in the Imageview without any resizing. If your image were small, it would’ve placed it in center.
2. centerInside
Scales the image uniformly, maintaining its aspect ratio. Both the dimension (width and height) of the image will be equal or less than the corresponding dimension of the imageview. The image is then centered in the view.
3. centerCrop
Scales the image uniformly, while maintaining its aspect ratio. Making width and the height of the image more than the imageview thereby cropping the image to fit inside the corresponding dimension. The image is then centered in the view.
4. fitXY
Scales the image by stretching it to fit its width and height to size of imageview.
5. fitCenter
Scales the image uniformly, maintaining its aspect ratio. Both the dimension (width and height) of the image will be equal or less than the corresponding dimension of the imageview. The image is then centered in the view.
6. fitStart
Scales the image uniformly, maintaining its aspect ratio. Both the dimension (width and height) of the image will be equal or less than the corresponding dimension of the imageview. The image is then aligned to the top of the ImageView.
7. fitEnd
Scales the image uniformly, maintaining its aspect ratio. Both the dimension (width and height) of the image will be equal or less than the corresponding dimension of the imageview. The image is then aligned to the bottom of the ImageView.
8. matrix
Scales the image using the image matrix while drawing.
How to adjust imageView width?
Did you noticed some white space while scaling image and also di you faced problem with fitting your image with respect to its width while maintaining its aspect ratio?
To fix this issue, Android imageview has adjustViewBound attribute.
adjustViewBound removes the whitespace and scales image whilst maintaining the aspect ratio. Here is the code for this:
<ImageView
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/adi"/>
YOu can achieve the same result in Java file using the following line of code:
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
To learn how to style your Android App Buttons, click here.