Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve feathering effect in Android?

Tags:

android

I am trying to create an Oval Bitmap and I need to get a feather effect around the margins,

Does anyone have any idea How I can achieve this ?

Thanks.

like image 392
cataHHH Avatar asked Jan 17 '23 01:01

cataHHH


1 Answers

You could consider the 'feather effect' as a gradial gradient, with the alpha fading from 100% to 0%.

Android offers the RadialGradient class for this purpose. You'll want to use the constructor where you can specify the control points for the radient, as you'll want the fading to start near the edge, not in the middle.

The one problem with Android's RadialGradient class is that it only supports perfect circles, not for ovals. To compensate for this, we'll just draw a perfect circle and scale afterwards.

Example code:

    private Bitmap makeFeatheredOval(int width, int height) { 

        // Determine largest dimension, use for rectangle.
        int size = Math.max( width, height);

        RadialGradient gradient = new RadialGradient(size / 2, size / 2, size / 2, 
            new int[] {0xFFFFFFFF, 0xFFFFFFFF, 0x00FFFFFF},
            new float[] {0.0f, 0.8f, 1.0f}, 
            android.graphics.Shader.TileMode.CLAMP); 
        Paint paint = new Paint(); 
        paint.setShader(gradient); 

        Bitmap bitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888); 
        Canvas canvas = new Canvas(bitmap); 
        canvas.drawCircle(size / 2, size / 2, size / 2, paint);

        // Scale the bitmap, creating an oval
        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);

        return bitmap; 
    }

Example image (it's the oval "moon" in the upper left corner):

Oval circle overlayed on demoscene awesomeness

Bonus points for everyone who recognizes that backdrop image.

like image 75
Paul-Jan Avatar answered Jan 20 '23 15:01

Paul-Jan