Search code examples
androidandroid-drawableandroid-color

Android, color filter only works in preview


I am trying to get a white oval shape with a gradient stroke, kind of like a colored shadow.

I Need the color to be dynamically changed, so I tried adding a ColorFilter to a drawable.

        Drawable pulseDrawable = getResources().getDrawable(R.drawable.touch_circle);
        pulseDrawable.setColorFilter(App.userColor, PorterDuff.Mode.LIGHTEN);
        setBackground(pulseDrawable);

This is what I get in the preview toolbar

But when I run the app I get this,(poorly drawn using paint) :

enter image description here

The circle is fine, but instead of color adding the glow/shadow. It filled all the rest of the view with blue color.

I tried maing the layertype software, but that didn't work.

So why is the preview rendering fine, while running the app doesn't? Is there a way I could fix this? I'm also open for other solutions like drawing the shape programmatically without a bitmap


Solution

  • I hope this was what you intended. I have created a drawable. You can play with the values till you get what works for you.

    shadow.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <item>
            <shape android:shape="oval">
                <size
                    android:width="100dp"
                    android:height="100dp"/>
                <gradient
                    android:startColor="#eee"
                    android:endColor="#0FFF"
                    android:gradientRadius="45%"
                    android:type="radial"/>
            </shape>
        </item>
        <item
            android:left="22dp"
            android:bottom="22dp"
            android:top="22dp"
            android:right="22dp">
            <shape
                android:shape="oval">
                <solid android:color="#FFF"/>
            </shape>
        </item>
    </layer-list>
    

    Code to change the color at runtime

    imgView = (ImageView) findViewById(R.id.imgView);
    Drawable bg = ContextCompat.getDrawable(getApplicationContext(), R.drawable.shadow);
    int color = ContextCompat.getColor(getApplicationContext(), R.color.colorAccent);
    bg.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    imgView.setBackground(bg);
    

    And here is the code for the imageView

    <ImageView
        android:id="@+id/imgView"
        android:layout_gravity="center"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/shadow"/>