Apply fading edges to ImageView

NullPointer picture NullPointer · Feb 19, 2014 · Viewed 8.7k times · Source

Is there any way to apply vertical/horizontal fading edges to an ImageView component?

I already tried android:fadingEdge but unfortunately this attribute is deprecated and will be ignored as of API level 14, Any ideas?

Answer

Vucko picture Vucko · Jul 11, 2017

I have found a neat workaround that worked perfectly for me. I needed to fade out the top and the bottom of the imageView (this approach works for any side though, simply create a different gradient). I wrapped the ImageView inside of a FrameLayout and put 2 Views to the top and bottom, after that, I created the xml's with gradients for the background of these and simply put them as backgrounds. Here's how it looks:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:adjustViewBounds="true" />
        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/fade_effect_heigth"
            android:layout_gravity="bottom"
            android:background="@drawable/custom_gradient_bottom"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/fade_effect_heigth"
            android:layout_gravity="top"
            android:background="@drawable/custom_gradient_top"/>
</FrameLayout>

Now the 2 Views are on top of the image view, and their gradient xml background files look like this (this is the top gradient, bottom is the same just flip the start/end color):

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
    android:angle="90"
    android:startColor="#00000000" <- black with 0 alpha, so transparent
    android:endColor="#000000" <- black color
    android:type="linear" />

You can choose the height of the fade that works for you, I chose 120dp and it served my needs well. Here's a screenshot from my emulator of the ImageView only:

enter image description here