4

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.

cataHHH
  • 223
  • 1
  • 4
  • 14

1 Answers1

9

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.

Paul-Jan
  • 16,746
  • 1
  • 63
  • 95
  • Hello thank you very much for your help, but I need to create the feather around an already created Bitmap(A cropped bitmap). This is what i use : Bitmap croppedImage = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(croppedImage); Rect dstRect = new Rect(0, 0, width, height); canvas.drawBitmap(initialBitmap, r, dstRect, null);finnaly for cropping: Path p = mCrop.getCropPath(); Canvas c = new Canvas(croppedImage); c.clipPath(p, Region.Op.DIFFERENCE); c.drawColor(0x00000000, PorterDuff.Mode.CLEAR); – cataHHH Mar 31 '12 at 15:01
  • Sorry do not know how clear it is ... I have tried to add all kinds of Paint effects for the CroppedImage but I never noticed anything on it's margins. – cataHHH Mar 31 '12 at 15:02
  • nice workaround by scaling the gradient circle to make an oval – gnorsilva May 18 '12 at 14:51
  • You should look at applying a gaussian filter – Aiden Strydom Jul 21 '13 at 13:21