Android crop background
Solution 1
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>
Solution 2
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
Solution 3
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)
.
Sebastian Nowak
Updated on July 19, 2020Comments
-
Sebastian Nowak almost 4 years
I have a
LinearLayout
with width set tofill_parent
and height towrap_content
. Now I want to give it a background from a png file, but doing it in a traditional way causes theLinearLayout
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
-
Ryan Langton over 10 yearsthis does not give enough detail
-
Zapnologica over 8 yearsHow to do transparent background? And does every item inform of it have to have a transparent background color?