English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Explanation of the Difference Between src and background in Android

The difference between the XML attributes src and background in ImageView:

background will be stretched according to the width and height given by the ImageView component, while src stores the original size of the image and will not be stretched. src is the image content (foreground), bg is the background, and both can be used at the same time.

In addition: scaleType only affects src; bg can set transparency, for example, in ImageButton, you can use android:scaleType to control the scaling method of the image, as shown in the following example code:

  <ImageView android:id="@+id/img" 
  android:src="@drawable/logo"
  android:scaleType="centerInside"
  android:layout_width="60dip"
  android:layout_height=""60dip"
  android:layout_centerVertical="true"/>

  Description: centerInside means scale the image proportionally so that the length (width) of the image is less than or equal to the corresponding dimension of the view.

  Note: The controlled image is a resource rather than a background, that is, android:src="@drawable/logo" rather than android:background="@drawable/logo". The dynamic loading of images in the program is similar, such as: imgView.setImageResource(R.drawable.*); rather than imgView.setBackgroundResource(R.drawable.*);

Append: More detailed explanation of scaleType:

CENTER /CENTER Display the image in the center of the view without scaling

CENTER_CROP / centerCrop Scale the image proportionally so that the length (width) of the image is greater than or equal to the corresponding dimension of the view

CENTER_INSIDE / centerInside Scale the image proportionally so that the length (width) of the image is less than or equal to the corresponding dimension of the view

FIT_CENTER / fitCenter Scale the image proportionally to the smallest edge of the view and display in the center

FIT_END / fitEnd Scale the image proportionally to the smallest edge of the view and display in the lower part of the view

FIT_START / fitStart Enlarge the image proportionally/Shrink to the smallest edge of the view and display in the upper part of the view

FIT_XY / fitXY Display the image without maintaining the aspect ratio to the size of the view

MATRIX / Draw with matrix

This is the compilation of materials on the difference between Android src and background, and we will continue to supplement relevant materials. Thank you all for your support to this site!

You May Also Like