6
votes

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.
} 
3

3 Answers

9
votes

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.

3
votes

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.

-1
votes
int StartHoriz,StartVert,BarWidth,BarHeight; // rect start, width and height
StartHoriz=0;
StartVert=100;
width = 100;
height=120;
CDC* pCDC = GetDC();      // Get CDC pointer
CRect Rect(StartHoriz,StartVert,BarWidth,BarHeight);  //create rectangle dimensions
pCDC->Rectangle(Rect);   //draw rectangle