Search code examples
androidandroid-layoutimageview

Dissolve a background drawable


I am trying to do something similar to this with the background image dissolving:

enter image description here

This is the code I'm using:

<LinearLayout
    android:id="@+id/layout"
    android:background="@color/yellow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizonal">        
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
</LinearLayout>

I'm programmatically setting the background image like this:

((ImageView)findViewById(R.id.image)).setBackground(ContextCompat.getDrawable(this, R.drawable.bg_image);

If I had to guess, I need to set the opacity of the layout as it's not the image that is dissolving but the layout surrounding it. I've searched and I think I need to use setAlpha but I don't want the entire image transparent.


Solution

  • You can make use of Gradient in XML resource.

    bg_gradient.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape android:shape="rectangle"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <gradient
            android:startColor="@color/blue"
            android:endColor="@android:color/transparent"/>
    
    </shape>
    

    activity_main.xml

    Set Image on the background layout and on top of that set gradient.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_200dp"
        android:orientation="vertical"
        android:background="@drawable/image"
        app:layout_constraintTop_toBottomOf="@id/textView_version">
    
        <LinearLayout
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:background="@drawable/bg_gradient"/>
    </LinearLayout>
    

    Result

    enter image description here