以前看到三原色的图案,一直很好奇是如何画出来。后来终于搞清楚了,其实很简单,实际上就是RGB三个分量的"位与"运算。
下面给出Win32绘制三原色图案的例子,特此记录在此:
1 #include <windows.h> 2 3 LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM); 4 5 6 int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow) 7 { 8 static TCHAR szAppName[]=TEXT("RGB_SRCPAINT"); 9 HWND hWnd; 10 MSG msg; 11 WNDCLASS wc= {sizeof(WNDCLASS)}; 12 wc.style=CS_HREDRAW|CS_VREDRAW; 13 wc.lpfnWndProc=WndProc; 14 wc.cbClsExtra=0; 15 wc.cbWndExtra=0; 16 wc.hInstance=hInstance; 17 wc.hIcon=LoadIcon(NULL,IDI_APPLICATION); 18 wc.hCursor=LoadCursor(NULL,IDC_ARROW); 19 wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); 20 wc.lpszMenuName=NULL; 21 wc.lpszClassName=szAppName; 22 if(!RegisterClass(&wc)) { 23 MessageBox(NULL,TEXT("error"),szAppName,MB_ICONERROR|MB_OK); 24 return 0; 25 } 26 hWnd=CreateWindow(szAppName,TEXT("RGB"),WS_OVERLAPPEDWINDOW, 27 320,120,500,500,NULL,NULL,hInstance,NULL); 28 29 // 30 ShowWindow(hWnd,iCmdShow); 31 UpdateWindow(hWnd); 32 while(GetMessage(&msg,NULL,0,0)) { 33 TranslateMessage(&msg); 34 DispatchMessage(&msg); 35 } 36 return msg.wParam; 37 } 38 // 39 void Circle(HDC dc,int ox,int oy,int r) 40 { 41 Ellipse(dc,ox-r,oy-r,ox+r,oy+r); 42 } 43 // 44 LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) 45 { 46 // 47 HDC hdc,hMemDC; 48 HBITMAP hBitmap; 49 HBRUSH hbrush; 50 RECT rc= {0,0,500,500}; 51 PAINTSTRUCT ps; 52 int ox=250,oy=210,r=100; 53 // 54 switch (message) { 55 case WM_PAINT : 56 hdc=BeginPaint(hWnd,&ps); 57 //MemDC 58 hMemDC = CreateCompatibleDC(hdc); 59 hBitmap = CreateCompatibleBitmap(hdc,500,500); 60 SelectObject(hMemDC,hBitmap); 61 //ClearScreen with Black 62 hbrush = CreateSolidBrush(RGB(0, 0, 0)); 63 SelectObject(hMemDC,hbrush); 64 FillRect(hdc,&rc,hbrush); 65 //RED 66 hbrush = CreateSolidBrush(RGB(255, 0, 0)); 67 SelectObject(hMemDC,hbrush); 68 //Ellipse(hMemDC,0+200,0+200+30,100+200,100+200+30); 69 Circle(hMemDC,ox,oy+0.8*r,r); 70 BitBlt(hdc,0,0,500,500,hMemDC,0,0,SRCPAINT); 71 //GREEN 72 hbrush = CreateSolidBrush(RGB(0, 255, 0)); 73 SelectObject(hMemDC,hbrush); 74 //Ellipse(hMemDC,0+200-26,0+200-15,100+200-26,100+200-15); 75 Circle(hMemDC,ox-0.866*0.8*r,oy-0.5*0.8*r,r); 76 BitBlt(hdc,0,0,500,500,hMemDC,0,0,SRCPAINT); 77 //BLUE 78 hbrush = CreateSolidBrush(RGB(0, 0, 255)); 79 SelectObject(hMemDC,hbrush); 80 //Ellipse(hMemDC,0+200+26,0+200-15,100+200+26,100+200-15); 81 Circle(hMemDC,ox+0.866*0.8*r,oy-0.5*0.8*r,r); 82 BitBlt(hdc,0,0,500,500,hMemDC,0,0,SRCPAINT); 83 // 84 DeleteObject(hBitmap); 85 DeleteDC( hMemDC ); 86 EndPaint (hWnd, &ps) ; 87 88 break; 89 case WM_DESTROY : 90 PostQuitMessage(0); 91 break ; 92 } 93 return DefWindowProc (hWnd, message, wParam, lParam) ; 94 }
时间: 2024-10-10 10:22:27