Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an android:background that doesn't stretch?

I found this great thread describing how to "eat the cake and have it too", i.e. use image for a Button instead of ImageButton (which doesn't allow SetText(), resizing, etc.).

This is achieved by using the View attribute:

android:background="@drawable/bgimage" 

The only problem with this is that it stretches the image to fit the button size.

Short of hard-coding a fixed button size (in pixels!), is there a way to tell Android not to stretch the background image at all and either crop or pad it?

like image 860
ef2011 Avatar asked May 05 '11 18:05

ef2011


People also ask

What size should android background image be?

The recommended wallpaper image size for a phone is 640 pixels wide X 960 pixels tall. The image has to be either in PNG or JPG format.

How do you stretch a background?

You can use the CSS background-size: cover; to stretch and scale an image in the background with CSS only. This scales the image as large as possible in such a way that the background area is completely covered by the background image, while preserving its intrinsic aspect ratio.


2 Answers

You can create an xml bitmap and use it as background for the view. To prevent stretching you can specify android:gravity attribute.

for example:

<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android"     android:src="@drawable/dvdr"     android:tileMode="disabled" android:gravity="top" > </bitmap> 

There are a lot of options you can use to customize the rendering of the image

http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap

like image 123
Santosh Avatar answered Oct 21 '22 01:10

Santosh


You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.

Code:

onCreate(Bundle bundle) {   // Set content layout, etc up here    // Now adjust button sizes   Button b = (Button) findViewById(R.id.somebutton);   int someDimension = 50; //50pixels   b.setWidth(someDimension);   b.setHeight(someDimension); } 
like image 37
Dr.J Avatar answered Oct 21 '22 01:10

Dr.J