1.問題描述
利用c++實現用鼠標點擊任意位置,在此位置繪制矩形。並且給兩個矩形重疊部分,塗上顏色加以區分。具體效果如下圖所示:
2.關鍵代碼
此程序關鍵之處在於對鼠標行為的捕獲,至於怎么求出兩個矩形的重疊部分就更簡單了。MFC框架有一個CRect類,這個類有一個IntersectRect()函數可以很容易的求出,兩個矩形重疊部分,IntersectRect()具體用法見IntersectRect百度百科。
1 BOOL CMFCApplication2Dlg::PreTranslateMessage(MSG * pMsg) 2 { 3 if (pMsg->message == WM_LBUTTONDOWN)//左鍵按下 4 { 5 if (Rect_count == 2) 6 { 7 Invalidate(); 8 Rect_count = 0; 9 } 10 startRect = true; 11 CPoint pt; 12 GetCursorPos(&pt); 13 points[0] = pt; 14 points[1] = pt; 15 } 16 else if (pMsg->message == WM_LBUTTONUP)//左鍵抬起 17 { 18 CBrush brush(RGB(5, 25, 255)); 19 CClientDC dc(this); 20 21 Rect_count += 1; 22 startRect = false; 23 CRect mRect; 24 GetClientRect(&mRect); 25 ClientToScreen(&mRect); 26 27 CPoint pt; 28 GetCursorPos(&pt); 29 points[1] = pt; 30 31 dc.Rectangle(points[0].x-mRect.left, points[0].y - mRect.top, points[1].x - mRect.left, points[1].y - mRect.top); 32 33 if (Rect_count == 1) 34 { 35 Rect1 = CRect(points[0], points[1]); 36 } 37 if (Rect_count == 2) 38 { 39 Rect2 = CRect(points[0], points[1]); 40 if (IntersectRect(interRect, Rect1, Rect2)) 41 { 42 interRect.SetRect(interRect.TopLeft().x - mRect.left, interRect.TopLeft().y - mRect.top, interRect.BottomRight().x - mRect.left, interRect.BottomRight().y - mRect.top); 43 dc.FillRect(interRect, &brush); 44 } 45 } 46 } 47 else if (pMsg->message == WM_MOUSEMOVE) //光標移動 48 { 49 CRect mRect; 50 GetClientRect(&mRect); 51 ClientToScreen(&mRect); 52 CClientDC dc(this); 53 dc.SetROP2(R2_NOT); //此為關鍵!!! 54 dc.SelectStockObject(NULL_BRUSH); //不使用畫刷 55 CPoint pt; 56 GetCursorPos(&pt); 57 if (true == startRect) 58 { 59 dc.Rectangle(points[0].x - mRect.left, points[0].y - mRect.top, points[1].x - mRect.left, points[1].y - mRect.top); 60 dc.Rectangle(points[0].x - mRect.left, points[0].y - mRect.top, pt.x - mRect.left, pt.y - mRect.top); 61 points[1] = pt; 62 } 63 } 64 return CDialog::PreTranslateMessage(pMsg); 65 }
以上代碼的個別變量的聲明如下(是在.h的頭文件里面聲明的):
1 //變量 2 CPoint points[2];//這倆個點分別代表矩形主對角線的兩個端點 3 bool startRect=false;//指示是否按下鼠標左鍵 4 int Rect_count = 0;//記錄畫了幾個矩形了 5 CRect Rect1,Rect2, interRect;//我們只畫兩個矩形,Rect1代表第一次畫的矩形,Rect2代表第二次畫的矩形,interRect代表兩個矩形相交的矩形
整個項目源代碼GitHub地址:https://github.com/wbi12138/DrawRectangle
另外避免出錯請用vs2015以上的版本打開項目。
2017-05-19 15:16:06 by 旱奇