一、位图绘制步骤
1.加载位图,这里要用到函数LoadImage( ),其函数原型如下:
HANDLE LoadImage(
HINSTANCE hinst, //实例句柄
LPCTSTR lpszName,//指向图像的名称
UINT uType, //指定图像类型,这里是装载位图
int cxDesired, //加载宽度
int cyDesired //加载高度
UINT fuLoad; //加载方式,这里是来自文件
};
2.建立与窗口兼容的内存DC
函数原型:HDC CreateCompatibleDC(HDC hdc);
功能:创建一个与指定设备兼容的内存设备上下文环境(DC);
函数原型:BOOL DeleteDC(HDC hdc);
功能:内存DC使用结束后,使用DeleteDC( )释放内存
3.选择位图对象
函数原型:HGDIOBJ SelectObject(HDC hdc, HGDIOBJ hgdiobj);
功能:选择一对象到指定的设备上下文环境中,该新对象替换先前的相同类型的对象
4.贴图
二、代码实现
#include "stdafx.h"
HINSTANCE hInst;
HBITMAP hbmp;//declare a bitmap object
HDC mdc; //declare a memory DC
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void MyPaint(HDC hdc);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
MyRegisterClass(hInstance);
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize =sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "canvas";
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
HDC hdc;
hInst = hInstance;
hWnd = CreateWindow("canvas", "绘图窗口" , WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
MoveWindow(hWnd,10,10,600,450,true);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
hdc = GetDC(hWnd);
mdc = CreateCompatibleDC(hdc);//create a DC-compatible environment
hbmp = (HBITMAP)LoadImage(NULL,"bg.bmp",IMAGE_BITMAP,600,400,LR_LOADFROMFILE);
SelectObject(mdc,hbmp);
MyPaint(hdc);
ReleaseDC(hWnd,hdc);
return TRUE;
}
void MyPaint(HDC hdc)
{
BitBlt(hdc,0,0,600,400,mdc,0,0,SRCCOPY);//把内存DC上的位图贴到设备DC上
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
MyPaint(hdc);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
DeleteDC(mdc);
DeleteObject(hbmp);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}