23
votes

This is my first graphics based project and to begin with I need to be able to draw a rectangle onto a bitmap with transparency and text.

I'm not sure where to begin with this. I've done a little research but can't seem to find an article that will allow me to add a semi transparent rectangle to an image.

What I will have is an image stream that I need to be able to manipulate.

Can someone please point me in the right direction for this?

A site with source would be great as I have never done any GDI work before.

2

2 Answers

38
votes

You can try something like this:

// Load the image (probably from your stream)
Image image = Image.FromFile( imagePath );

using (Graphics g = Graphics.FromImage(image))
{
   // Modify the image using g here... 
   // Create a brush with an alpha value and use the g.FillRectangle function
}

image.Save( imageNewPath );

Edit: the code to create a semi transparency gray brush

Color customColor = Color.FromArgb(50, Color.Gray);
SolidBrush shadowBrush = new SolidBrush(customColor);
g.FillRectangles(shadowBrush, new RectangleF[]{rectFToFill});
5
votes

To get started you need to create a Graphics context from the image that you want to modify. See here.

// Create image.
Image imageFile = Image.FromFile("SampImag.bmp");

// Create graphics object for alteration.
Graphics newGraphics = Graphics.FromImage(imageFile);

Once you have the Graphics object you can use its many methods to draw onto the image. In your example you would use DrawRectangle method with an ARGB color to create a semi-transparent rectangle on your image.

You can then display the image to a screen control or save it to disk.