I want to display an image as background in my app. Now I used this statement: android:background="@drawable/background"
in <LineraLayout>
. Here is the .xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="overbit.user.MainActivity"
android:background="@drawable/background">
</LinearLayout>
Now I get this output:
But I want it like this:
Maybe someone of you can help me. Thanks.
There is BitmapDrawable, which allows to do it. First you need to create a drawable resource as follows (let it be a file in the project resources res/drawable/mybg.xml
):
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background"
android:gravity="center" />
And then specify it as a background resource in your layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="overbit.user.MainActivity"
android:background="@drawable/mybg">
</LinearLayout>
You need to change the image's size itself in photoshop or something to achieve the desired result (still this can be very difficult because of various screen sizes of android smartphones). A workaround can be to change your parent layout to Relativelayout and then use a an imageview to show your picture like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" xmlns:ads="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" //make sure its match parent android:layout_height="match_parent"// and this one also android:src="@drawable/yourBackgroundImage" android:scaleType="..."/> <LinearLayout>put your childviews here</LinearLayout>
there are 4-5 options available for android:scaleType... experiment with them, till you get your desired result. Also note that you need to use android:src rather than android:background attribute of the imageview
You can accomplish what you're trying to do by using BitmapRegionDecoder.
From the docs:
BitmapRegionDecoder can be used to decode a rectangle region from an image. BitmapRegionDecoder is particularly useful when an original image is large and you only need parts of the image.
It allows you to decode a Rect area of a particular Bitmap fairly easily, the only thing you need to do is calculate your Rect region to decode relative to the Bitmap.
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