androidxmlandroid-5.0-lollipopandroid-4.2-jelly-beanandroid-4.1-jelly-bean

Circular Button not working on android API-16 (Jelly Bean)


I want to create a simple circular ImageButton as shown below, which is supported in android API versions of 16 or higher.

<ImageButton android:layout_width="70dp"
 android:layout_height="70dp"
 android:id="@+id/myButton"
 android:background="@drawable/circular_button" />

My circular_button.xml inside drawable folder looks like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="oval">
            <solid android:color="#fa09ad"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="#c20586"/>
        </shape>
    </item>
</selector>

Things work fine on android Lollipop (API 21) and this how the ImageButton looks:

enter image description here

But on older android versions (API 16), it looks like this:

enter image description here

Any idea how to get this solved? Thanks!


Solution

  • Edit My Mistake: Please try below code, i used it in my own code and it is working perfectly for round images.

    public class ImageHelper {
        public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                    .getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
    
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;
    
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
    
            return output;
        }
    }