I would like to display an image as the screen background and since I am having difficulties with image view's scale_type in the xml, I am doing the computations with image ratio and screen dimensions in a function, nothing too complicated
public static Bitmap BitmapToView(Bitmap img, View v) { int imgWidth = img.getWidth(); int imgHeight = img.getHeight(); int bckWidth = v.getWidth(); int bckHeight = v.getHeight(); float ratio1 = (float) bckWidth / imgWidth; float ratio2 = (float) bckHeight / imgHeight; float maxRatio = Math.max(ratio1, ratio2); int newHeight = Math.max((int) (imgHeight * maxRatio), bckHeight); int newWidth = Math.max((int) Math.ceil(imgWidth * maxRatio), bckWidth); Bitmap tmp_image = Bitmap.createScaledBitmap(img, newWidth, newHeight, true); Bitmap ret_image = Bitmap.createBitmap(tmp_image, Math.abs(newWidth - bckWidth)/2, Math.abs(newHeight - bckHeight)/2, bckWidth, bckHeight); tmp_image.recycle(); return ret_image; } Options options = new Options(); options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeFile(imgFilePath, options); Bitmap newImage = BitmapToView(img, findViewById(R.id.myRelativeLayout); // RelariveLayout takes up the whole screen ; failing on Samsung Galaxy S4 findViewById(R.id.myRelativeLayout).setBackground(new BitmapDrawable(newimage)); And sometimes I get an out of memory exception I have tried to use .recycle() here and there but then I get "Canvas: trying to use a recycled bitmap"
Any idea ? Thanks