Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale image keeping its aspect ratio in background drawable

How do I make a background image fit the view but keep its aspect ratio when using <bitmap /> as a background drawable XML? None of <bitmap>'s android:gravity values gives the desired effect.

like image 717
tilex Avatar asked Mar 27 '12 13:03

tilex


People also ask

How do I resize an image in ImageView to keep the aspect ratio?

However, make sure you're setting the image to the ImageView using android:src="..." rather than android:background="..." . src= makes it scale the image maintaining aspect ratio, but background= makes it scale and distort the image to make it fit exactly to the size of the ImageView.

What is the preferred image format for the drawable?

Supported file types are PNG (preferred), JPG (acceptable), and GIF (discouraged).

What is adjust view bounds in android?

android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView control to maintain the aspect ratio of the image displayed through it. android:resizeMode—The resizeMode attribute is used to make a control resizable so we can resize it horizontally, vertically, or around both axes.


1 Answers

It is impossible to achieve manipulating background attribute within xml-files only. There are two options:

  1. You cut/scale the bitmap programmatically with Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) and set it as some View's background.

  2. You use ImageView instead of background placing it as the first layout's element and specify android:scaleType attribute for it:

    <RelativeLayout     android:layout_width="fill_parent"     android:layout_height="fill_parent" >      <ImageView         android:layout_width="wrap_content"         android:layout_height="wrap_content"          android:src="@drawable/backgrnd"         android:scaleType="centerCrop" />      ...      rest layout components here      ...  </RelativeLayout> 
like image 120
a.ch. Avatar answered Sep 23 '22 16:09

a.ch.