Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ MFC How to Draw Alpha transparent Rectangle

Tags:

c++

paint

mfc

in a C++ MFC application. using the dc of ( CPaintDC dc(this); )

How do i draw a rectangle ( LPRECT ) with an alpha transparency that i can adjust.?

Following is an example c# code which i need to convert into C++

private void pictureBox1_Paint(object sender, PaintEventArgs e)  
{
    Graphics g = e.Graphics;
    Color color = Color.FromArgb(75,Color.Red); //sets color Red with 75% alpha transparency

    Rectangle rectangle = new Rectangle(100,100,400,400);
    g.FillRectangle(new SolidBrush(color), rectangle); //draws the rectangle with the color set.
} 
like image 660
Mafahir Fairoze Avatar asked Nov 03 '10 13:11

Mafahir Fairoze


People also ask

How do you fill a shape with Alpha and color?

To fill an opaque shape, set the alpha component of the color to 255. To fill a semitransparent shape, set the alpha component to any value from 1 through 254.

How to draw a transparent hatch rectangle on screen?

>Regards! How to draw a transparent hatch rectangle on screen? the screen DC setting the background mode to TRANSPARENT. bitmap will be treated as being transparent. >Hi, everyone!

What is the alpha value of a shape in illustrator?

When you fill a semitransparent shape, the color of the shape is blended with the colors of the background. The alpha component specifies how the shape and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weight on the shape color.

What are transparent graphics shapes?

As you can see from this figure, the transparent graphics shapes (lines, rectangle, ellipse and text) are drawn on top of an image. Figure 1. The code listed in Listing 2 creates and draws few graphics shapes and on top of that, it draws a transparent image.


2 Answers

You need to look into GDI+. Its a bit of a faff but you can create a "Graphics" object as follows:

Gdiplus::Graphics g( dc.GetSafeHdc() );
Gdiplus::Color color( 192, 255, 0, 0 );

Gdiplus::Rect rectangle( 100, 100, 400, 400 );
Gdiplus::SolidBrush solidBrush( color );
g.FillRectangle( &solidBrush, rectangle );

Don't forget to do

#include <gdiplus.h>

and to call

 GdiplusStartup(...);

somewhere :)

You'll notice it's pretty damned similar to your C# code ;)

Its worth noting that the 75 you put in your FromArgb code doesn't set 75% alpha it actually sets 75/255 alpha or ~29% alpha.

like image 105
Goz Avatar answered Oct 20 '22 18:10

Goz


GDI (and thus MFC) has no decent support for drawing with an alpha. But GDI+ is available in C++ code as well. Use #include <gdiplus.h> and initialize it with GdiplusStartup(). You can use the Graphics class, create one with its Graphics(HDC) constructor from your CPaintDC. And use its FillRectangle() method. The SDK docs are here.

like image 32
Hans Passant Avatar answered Oct 20 '22 20:10

Hans Passant