4

How to draw a bitmap with a given color set as transparent?
For example I want all white pixels to be transparent.

Tomek Tarczynski
  • 2,785
  • 8
  • 37
  • 43

3 Answers3

14

You need to set the Alpha value for the paint you're passing to the Bitmap.

http://developer.android.com/reference/android/graphics/Paint.html#setAlpha%28int%29

Values vary from 0-255

EDIT:

Paint p = new Paint();
//Set Blue Color
p.setColor(Color.WHITE);
//Set transparency roughly at 50%
p.setAlpha(125);
Manish Burman
  • 3,069
  • 2
  • 30
  • 35
  • I don't get it. How can I set some color to be transparent if there is only one parameter? To choose a color I need at least three parameters. Could You write a short example how to display a bitmap on the surface view with a transparent white color? – Tomek Tarczynski Mar 21 '11 at 08:27
  • 4
    I should've replied to this sooner but here goes. p.setColor(Color.White) sets the color of your bitmap to white. Transparency is controlled by one value - aplha which goes between 0 & 255. 0 is completely transparent, 255 is completely opaque - hence p.setAlpha(125) is somewhere in the middle. Does that clear things up? – Manish Burman Aug 02 '11 at 12:51
  • 1
    This just sets the entire bitmap to be semi-transparent it does not give the intended effect. – Brian Griffey Nov 27 '12 at 20:54
  • Yeah, I didn't realize that the op wanted to make only one color transparent without affecting the other colors in the bitmap. I misunderstood what he was asking for. Sorry! – Manish Burman Nov 28 '12 at 01:59
  • 3
    Oddly enough, while this answer failed to answer the OP's question, it did answer the one I googled for. :) Thanks Manish! – William T. Mallard Aug 31 '13 at 18:47
4

you need to check every pixel of image and change its color. you will get your answer in this Post

Community
  • 1
  • 1
Saurabh Pareek
  • 7,126
  • 4
  • 28
  • 29
1

Another approach is drawing in trasparent color on your canvas (drawing holes). The bitmapu needs alpha channel.

    //Set transparent paint - you need all of these three
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
    paint.setColor(Color.TRANSPARENT);

    // Do you wanna soften?
    // Set paint transparency:
    // 0 = transparent ink, no visible effect
    // 255 = full ink, hole in the bitmap
    p.setAlpha(192);

    // Do you want some blur?
    // Set blur radius in pixel
    paint.setMaskFilter(new BlurMaskFilter(10, Blur.NORMAL));
Rudy
  • 181
  • 2
  • 10