MFC繪圖可以很明顯的看到先前畫(huà)的矩形會(huì)被后來(lái)畫(huà)的矩形所覆蓋掉,這時(shí)候我需要后來(lái)畫(huà)的矩形透明。那么我們要怎么來(lái)實(shí)現(xiàn)呢?
方法一
可以利用GetStockObject 這個(gè)函數(shù)來(lái)實(shí)現(xiàn),GetStockObject 函數(shù)獲取的是一個(gè)畫(huà)刷句柄。
//創(chuàng)建透明畫(huà)刷
RECT rect;
rect.top = 0;
rect.left = 0;
rect.right = 100;
rect.bottom = 100;
static HBRUSH m_brush; //畫(huà)刷句柄
m_brush = (HBRUSH)GetStockObject(NULL_BRUSH);
//將空畫(huà)刷選入設(shè)備描述表
SelectObject(hdc, m_brush);
//繪制一個(gè)矩形
Rectangle(hdc, one_w, y, one_w + 100, y+100);//繪制一個(gè)填充為RGB(60,38,99)的矩形
以上雖然能實(shí)現(xiàn)看到先前繪制的矩形,但是我想要的是顏色透明。顯然方法一是不能滿(mǎn)足我的,找了很多資料并沒(méi)有解決,希望看到的網(wǎng)友能賜教,感謝?。。?/strong>
顏色透明實(shí)現(xiàn)不了那我們更換思路,添加背景色。
方法二
使用函數(shù)SetBkColor,SetBkMode設(shè)置整個(gè)窗口的背景色。SetBkColor是背景顏色,SetBkMode是背景模式。
// SetMode 模式
SetBkColor(hdc, RGB(255, 255, 0));
SetBkMode(hdc, TRANSPARENT);
TextOutA(hdc, 256, 24, "hello world", 11);
// 非SetMode模式
SetBkColor(hdc, RGB(255, 255, 0));
// SetBkMode(hdc, TRANSPARENT);
TextOutA(hdc, 256, 24, "hello world", 11);
注意:此方法只能用于文本,填充畫(huà)刷和畫(huà)筆不是實(shí)線(xiàn)時(shí)。看下圖

ponglyon.png
測(cè)試代碼:
//setp2
SetBkColor(hdc, RGB(255, 255, 0));
TextOutA(hdc, 0, 600, "hello world", strlen("hello world"));
//SetBkMode(hdc, OPAQUE);
//1.用m_brush填充矩形
static HBRUSH m_brush; //畫(huà)刷句柄 用來(lái)填充圖形
m_brush = CreateHatchBrush(HS_BDIAGONAL, RGB(255, 255, 255));
RECT rect;
rect.top = 600;
rect.left = 100;
rect.right = 100 + 100;
rect.bottom = 600 + 100;
FillRect(hdc, &rect, m_brush);
//2.用虛線(xiàn)畫(huà)筆畫(huà)一條直線(xiàn)
HPEN hPen;
hPen = CreatePen(PS_DASH, 1, RGB(0, 255, 0));
SelectObject(hdc, hPen);
MoveToEx(hdc, 300, 600, NULL);
LineTo(hdc, 400, 0);
方法二會(huì)將整個(gè)窗口添加上背景色,不理想。
方法三
FillRect()函數(shù):用指定的畫(huà)刷填充矩形, 函數(shù)包括矩形的左上邊界,但不包括矩形的右下邊界。
RECT rect;
rect.top = one_w;
rect.left = y;
rect.right = one_w + 100;
rect.bottom = y+ 100;
static HBRUSH m_brush; //畫(huà)刷句柄 用來(lái)填充圖形
m_brush = CreateHatchBrush(HS_BDIAGONAL, RGB(255, 255, 0));
FillRect(hdc, &rect, m_brush);
在線(xiàn)求更完美創(chuàng)建透明顏色畫(huà)刷的方法!??!