如何在C++ MFC中绘制Alpha透明矩形

6

在使用C++ MFC应用程序时,使用(CPaintDC dc(this);)的dc

如何绘制一个带有可调节alpha透明度的矩形(LPRECT)?

以下是需要转换为C ++的示例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个回答

9

您需要了解GDI+。虽然有些麻烦,但您可以按照以下方式创建“Graphics”对象:

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 );

不要忘记去做

#include <gdiplus.h>

并调用

 GdiplusStartup(...);

某个地方 :)

你会发现这与你的C#代码非常相似 ;)

值得注意的是,你在 FromArgb 代码中输入的75并不是设置了75%的 alpha ,而实际上是设置了 75/255 的 alpha 或者大约29% 的 alpha。


如果我调用GdiplusStartup();,那么我是否必须调用GdiplusShutdown?我认为我必须这样做。如果我必须这样做,那么它应该在Paint事件中吗? - Mafahir Fairoze
1
GdiplusStartup通常应该从您的MFC应用程序的InitInstance函数中调用一次。然后,当您的应用程序退出时,应调用GdiplusShutdown一次。 - Goz

3

GDI(以及MFC)对于使用alpha进行绘图没有很好的支持。但是,在C++代码中可以使用GDI+。使用#include <gdiplus.h>并使用GdiplusStartup()进行初始化。您可以使用Graphics类,使用其Graphics(HDC)构造函数从您的CPaintDC创建一个。然后使用其FillRectangle()方法即可。SDK文档在此处


-1
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接