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?
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.
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.
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
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With