I find it really hard to handle images with Android, I think it\'s the hardest part of Android development...
1) I have an image, I want it to be the background of m
I recently had to do something similar to this. So here are some tricks.
If you want to preserve the aspect ratio of your image, use this in a relative layout. Note:The layout width and height of the relative layout should be match_parent or fill_parent.
This will crop the image from its center. There are other options available as well. Use fitXY instead of centerCrop to fit, it to the device with no consideration to the aspect ratio. For Best results with this, use a considerably large image.
Another option would be to sufficiently add a solid background colour to your image and increase its size. Load it into your drawables folder and use this class.
public class ReturnBackGroundImage {
//To avoid java.lang.OutOfMemory exceptions, check the dimensions of a bitmap before decoding it,
// unless you absolutely trust the source to provide you with predictably sized image data that
// comfortably fits within the available memory.
public static Bitmap decodeSampledBitmapFromResource(Resources resources, int resId, int reqWidth, int reqHeight, boolean UseDeviceHeight, Activity activity) {
if(UseDeviceHeight){
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
reqHeight = metrics.heightPixels;
reqWidth = metrics.widthPixels;
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, options);
return ResizeImage(resources,options,resId,reqWidth,reqHeight);
}
public static Bitmap ResizeImage(Resources resources,BitmapFactory.Options options, int resId, int reqWidth, int reqHeight) {
double imageHeight = options.outHeight;
double imageWidth = options.outWidth;
double ratio = reqHeight / imageHeight;
int newImageWidth = (int) (imageWidth * ratio);
Bitmap bMap = BitmapFactory.decodeResource(resources, resId);
return getResizedBitmap(bMap, reqHeight, newImageWidth);
}
}
Use it as follows
ImageView v = (ImageView)findViewById(R.id.bgloginpagew);
v.setImageBitmap(ReturnBackGroundImage.decodeSampledBitmapFromResource(getResources(),R.drawable.mainbgforapp,0,0,true,walkThroughActivity.this));
This is a modified version of the example from the android website.
If someone needs the ratios for saving different sized images, it is
afaik these ratios are only valid for square images. Thought I'd put it out there for some guy who needed them, like I did.