Search code examples
androidandroid-drawableandroid-buttonandroid-vectordrawable

How can I apply an alpha mask to an Android drawable?


In my application, I need to change the background color of a button in response to certain events. That works fine by setting creating a drawable, setting its paint and using that drawable as the button background:

    ShapeDrawable drawable = new ShapeDrawable(roundRectShape);
    drawable.getPaint().setColor(color);
    b.setBackground(drawable);

Now, I want to overlay an alpha mask onto that drawable, creating a "striped" button. Here's how it should look like for a blue and a black button (assuming white as the background color, but these sections should really be 100% transparent):

enter image description here

I made this alpha mask in Inkscape, and successfully imported it as a vector asset. I might need to convert it to a bitmap of sorts, but I'm not sure.

I've read a bunch of articles and SO questions mentioning PorterDuff matrices to apply, but haven't been able to translate these into solving my current problem.

Anyone know how to do this?


Here's another visualization, hopefully making things clearer. The background color of the parent view of the button is pale pink here, and the button border is outlined in red (but should really be invisible in the end product):

enter image description here


Solution

  • So, I figured out how to do this, albeit not using an SVG - too many issues there.

    First, I switched from using a Button to ImageButton. Then I applied the following style:

    <style name="stripedButton">
        <item name="android:layout_gravity">left</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:stateListAnimator">@null</item>
        <item name="android:clickable">true</item>
        <item name="android:elevation">0dp</item>
        <item name="android:longClickable">true</item>
        <item name="layout_widthPercent">70%</item>
        <item name="android:src">@drawable/fade_in_bars</item>
        <item name="android:tint">@color/RED</item>
        <item name="android:background">@null</item>
        <!-- Stretch image to fill entire button. -->
        <item name="android:scaleType">fitXY</item>
    </style>
    

    fade_in_bars is just the png version of the alpha mask shown in the original question. The color can be set in XML or programmatically using the tint attribute. I don't quite understand why I need to set the background to null, but it looks strange otherwise. Finally, setting the scaleType to fitXY is needed so that all the stripes are shown, regardless of the size of the button on a particular display.

    Here's what it looks like:

    enter image description here