Android crop background

31,075

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).

Share:
31,075
Sebastian Nowak
Author by

Sebastian Nowak

Updated on July 19, 2020

Comments

  • Sebastian Nowak
    Sebastian Nowak almost 4 years

    I have a LinearLayout with width set to fill_parent and height to wrap_content. Now I want to 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

  • Ryan Langton
    Ryan Langton over 10 years
    this does not give enough detail
  • Zapnologica
    Zapnologica over 8 years
    How to do transparent background? And does every item inform of it have to have a transparent background color?