简体   繁体   中英

C++ MFC How to Draw Alpha transparent Rectangle

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

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM