Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Circular Gradient Alpha Mask

Tags:

android

Is there a way to draw a circular gradient mask on a bitmap in Android? Trying to produce something similar to a foggy window. Click the window and a transparent circle shows up revealing whats behind the window. Prefferably using a gradient so the center of the circle is completely transparent and the further out from the center the less transparent. Is this possible?

I'm new to Android so any code samples would be appreciated.

Thanks.

like image 276
Someone Else Avatar asked Nov 11 '10 22:11

Someone Else


1 Answers

private void drawFoggyWindowWithTransparentCircle(Canvas canvas,
        float circleX, float circleY, float radius) {

    // Get the "foggy window" bitmap
    BitmapDrawable foggyWindow = 
        (BitmapDrawable) getResources().getDrawable(R.drawable.foggy_window);
    Bitmap foggyWindowBmp = foggyWindow.getBitmap();

    // Create a temporary bitmap
    Bitmap tempBitmap = Bitmap.createBitmap(
            foggyWindowBmp.getWidth(),
            foggyWindowBmp.getHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas tempCanvas = new Canvas(tempBitmap);

    // Copy foggyWindowBmp into tempBitmap
    tempCanvas.drawBitmap(foggyWindowBmp, 0, 0, null);

    // Create a radial gradient
    RadialGradient gradient = new android.graphics.RadialGradient(
            circleX, circleY,
            radius, 0xFF000000, 0x00000000,
            android.graphics.Shader.TileMode.CLAMP);

    // Draw transparent circle into tempBitmap
    Paint p = new Paint();
    p.setShader(gradient);
    p.setColor(0xFF000000);
    p.setXfermode(new PorterDuffXfermode(Mode.DST_OUT));
    tempCanvas.drawCircle(circleX, circleY, radius, p);

    // Draw tempBitmap onto the screen (over what's already there)
    canvas.drawBitmap(tempBitmap, 0, 0, null);
}
like image 186
Alex Jasmin Avatar answered Oct 13 '22 22:10

Alex Jasmin