Android crop background
I have a LinearLayout
with width set to fill_parent
and height to wrap_content
. Now I want 开发者_如何学JAVAto give it a background from a png file, but doing it in a traditional way causes the LinearLayout
to resize in order to show the whole background instead of cropping the additional part.
How can I set the background of LinearLayout
so it won't resize?
Thanks
It appears that such thing is achievable only using the ImageView
and setting the scaleType
parameter accordingly. A quick workaround is to use FrameLayout
and put the ImageView
under another layout with transparent background.
Code:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/background" />
</FrameLayout>
The default behaviour of background bitmaps is to fill the container completely and grow the horizontal and vertical size of the container if needed. The solution is to create a drawable bitmap resource and changing the gravity.
Check the following link and look for the possible gravity values. Your view should then just reference the drawable resource and you should be fine.
http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
I solved this one by subclassing LinearLayout
and overriding the onMeasure(int,int)
callback, then updating the layout XML to use my new layout type. I'm not at liberty to post that exact code, but what I did was invoke the super.onMeasure(int,int)
implementation and check whether the measured height came back as the exact height of my background image. If so, I grab the measured height of all child views, then calculate a new height value and pass it to setMeasuredDimension(int,int)
.
put this code in the xml activity, for example activity_main.xml
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/image" />
精彩评论