What is the difference between src and background of ImageView

AndroidBackgroundImageviewSrc

Android Problem Overview


I am a puzzled about using src or background for an ImageView.

I know the former means the content of this ImageView and the latter means the background of the ImageView.

But how to decide which one to use? I don't see the difference.

Android Solutions


Solution 1 - Android

All views can take a background image.

The src to an ImageView has additional features:

  • different scaling types
  • adjustViewBounds for setting bounds to match image dimensions
  • some transformations such as alpha-setting

And more that you may find in the docs.

Solution 2 - Android

  1. when you use android:background, image will be set to fit on ImageView area(i.e according to width and height of ImageView). It doesn't matter if the image is smaller or larger than ImageView.

  2. when you use android:src, then image will display in its original size. No automatic scaling, adjustments will happen. Note: Using android:src, we can get additional benefit of adjustViewBounds property

Solution 3 - Android

If you set an image to be the background of your ImageView, then the image will scale to whatever size the ImageView is. Other than that, src is a foreground image and background is a background image. Pretty much as it implies.

Solution 4 - Android

The difference between XML attribute src and background in ImageView:

The background will stretch according to the length given by the ImageView component, and SRC will hold the size of the original image without stretching. SRC is the picture content (foreground), BG is the background, can be used at the same time.

In addition: ScaleType only works on SRC; BG can set transparency, for example, in ImageButton, you can use Android:scaletype to control how the image is scaled, sample code as follows:

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

Feel free to ask doubt if you get any.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpeter_fengView Question on Stackoverflow
Solution 1 - AndroidMatthew WillisView Answer on Stackoverflow
Solution 2 - AndroidKetan PatelView Answer on Stackoverflow
Solution 3 - AndroidBigFwooshView Answer on Stackoverflow
Solution 4 - AndroidAditya ShendeView Answer on Stackoverflow