Reputation: 807
I am trying to set a image like background image in a layout (by xml or by code)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/my_image">
or
View myLayout= findViewById( R.id.main_layout);
myLayout.setBackgroundResource(R.drawable.my_image);
My problem is than android fix the image in the all background screen, resizing and modifying the image ratio.
How can I set a image, and that the image takes only the neccesary space? (without image resizing)
Upvotes: 8
Views: 21282
Reputation: 5354
Put your LinearLayout inside a RelativeLayout and add an ImageView to that RelativeLayout.
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" >
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@drawable/my_image" />
<LinearLayout
android:id="@+id/main_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
Note that ImageView is the first element in RelativeLayout, causing it to be drawn in background. By declaring fitXY and adjustViewBounds in ImageView, you ensure your image keeps its ratio. You could as well turn adjustViewBounds off and choose another scaleType like fitStart or centerCrop. They also keep aspect ratio.
Upvotes: 6
Reputation: 15267
Without adding an ImageView
to the layout, if the image is smaller than the space, you can create an xml bitmap resource like the following, and use this in place of the original background image:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background"
android:gravity="center"
/>
Upvotes: 7
Reputation: 3159
"setBackground" resize the image to fill the View(LinearLayout).
Please add ImageView in LinearLayout or RelativeLayout, and then use setImageResource to achieve that.
Upvotes: 0
Reputation: 180
Jst take another layout inside LinearLayout.
Keet it as Relative so that u can keep that layout wherever You want. and in that Relative Layout u keep imageView.
And ya that's it i think what u want....
Upvotes: 0