views:

1256

answers:

2

Hello!

I want to draw an image over other without drawing its backgroud. The image that I want to draw it's a star. I want to put some stars over a map image.

The problem is that the star's image has a white backgroud and when I draw over the map the white background appears.

My method to draw the star is like this:

Graphics graphics = Graphics.FromImage(map); 
Image customIcon = Image.FromFile("../../star.png");
graphics.DrawImage(customIcon, x, y);

I tried with transparent backgroud images (PNG and GIF formats), and it always draw something surrounding the star. How can I draw a star without its background?

The program is for Windows Mobile 5.0 and above, with Compact Framework 2.0 SP2 and C#.

I tried with this code:

Graphics g = Graphics.FromImage(mapa);
Image iconoPOI = (System.Drawing.Image)Recursos.imagenPOI;
Point iconoOffset = new Point(iconoPOI.Width, iconoPOI.Height);

System.Drawing.Rectangle rectangulo;
ImageAttributes transparencia = new ImageAttributes();
transparencia.SetColorKey(Color.White, Color.White); 

rectangulo = new System.Drawing.Rectangle(x, y, iconoPOI.Width, iconoPOI.Height);
g.DrawImage(iconoPOI, rectangulo, x, y, iconoPOI.Width, iconoPOI.Height, GraphicsUnit.Pixel, transparencia);

But I don't see anything on map.

X and Y are de coordinates where I want to draw the iconoPOI which it's a PNG imagen with a white background.

Thank you!

A: 

Normally this task is pretty complicated (you have to tap the windows API BitBlt function and create a black-and-white mask image and other stuff), but here's a simple way to do it.

Assuming you have one bitmap for your background image (bmpMap) and one for your star image (bmpStar), and you need to draw the star at (xoffset, yoffset), this method will do what you need:

for (int x = 0; x < bmpStar.Width; x++)
{
    for (int y = 0; y < bmpStar.Height; y++)
    {
        Color pixel = bmpStar.GetPixel(x, y);
        if (pixel != Color.White)
        {
            bmpMap.SetPixel(x + xoffset, y + yoffset, pixel);
        }
    }
}

SetPixel and GetPixel are incredibly slow (the preferred way is to use the bitmap's LockBits method - there are questions here on SO that explain how to use it), but this will get you started.

MusiGenesis
+1  A: 

One valid answer can be found here:

Answer

Thank you!

VansFannel

related questions