简单动画的实现
LRESULT CALLBACK WndProc(HWND hwnd,UINT iMsg,WPARAM wParam,LPARAM lParam)
{
static HBITMAP hBitmap;
static int cxClient,cyClient,xCenter,yCenter,cxTotal,cyTotal,
cxRadius,cyRadius,cxMove,cyMove,xPixel,yPixel;
HBRUSH hBrush;
HDC hdc,hdcMem;
int iScale;
switch(iMsg)
{
case WM_CREATE:
hdc=GetDC(hwnd);
//获取用于画线的设备像素的相对宽度
xPixel=GetDeviceCaps(hdc,ASPECTX);
//获取用于画线的设备像素的相对高度
yPixel=GetDeviceCaps(hdc,ASPECTY);
ReleaseDC(hwnd,hdc);
//设置定时器
SetTimer(hwnd,ID_TIMER,50,NULL);
return 0;
case WM_SIZE:
xCenter=(cxClient=LOWORD(lParam))/2;
yCenter=(cyClient=HIWORD(lParam))/2;
//小球的直径是客户区高、宽中较小的十六分之一
iScale=min(cxClient*xPixel,cyClient*yPixel)/16;
//x方向半径比例(把单位消除)
cxRadius=iScale/xPixel;
//y方向半径比例(把单位消除)
cyRadius=iScale/yPixel;
//每次移动距离,最小为1,x,y方向同步
cxMove=max(1,cxRadius/2);
cyMove=max(1,cyRadius/2);
//应该是所操作的范围
cxTotal=2*(cxRadius+cxMove);
cyTotal=2*(cyRadius+cyMove);
if(hBitmap)
DeleteObject(hBitmap);
hdc=GetDC(hwnd);
//创建内存设备上下文
hdcMem=CreateCompatibleDC(hdc);
//创建位图
hBitmap=CreateCompatibleBitmap(hdc,cxTotal,cyTotal);
ReleaseDC(hwnd,hdc);
SelectObject(hdcMem,hBitmap);
//内存中画矩形
Rectangle(hdcMem,-1,-1,cxTotal+1,cyTotal+1);
//创建一个有45度交叉阴影的刷子
hBrush=CreateHatchBrush(HS_DIAGCROSS,0L);
//选入内存
SelectObject(hdcMem,hBrush);
//设置背景颜色
SetBkColor(hdcMem,RGB(255,0,255));
//画椭圆
Ellipse(hdcMem,cxMove,cyMove,cxTotal-cxMove,cyTotal-cyMove);
DeleteDC(hdcMem);
DeleteObject(hBrush);
return 0;
case WM_TIMER:
if(!hBitmap)
break;
hdc=GetDC(hwnd);
hdcMem=CreateCompatibleDC(hdc);
SelectObject(hdcMem,hBitmap);
//在相应位置显示出来
BitBlt(hdc,xCenter-cxTotal/2,yCenter-cyTotal/2,cxTotal,cyTotal,hdcMem,0,0,SRCCOPY);
ReleaseDC(hwnd,hdc);
DeleteDC(hdcMem);
xCenter+=cxMove;
yCenter+=cyMove;
//碰到边以后,向回反
if((xCenter+cxRadius>=cxClient)||(xCenter-cxRadius<=0))
cxMove=-cxMove;
if((yCenter+cyRadius>=cyClient||(yCenter-cyRadius)<=0))
cyMove=-cyMove;
return 0;
case WM_DESTROY:
if(hBitmap)
DeleteObject(hBitmap);
KillTimer(hwnd,ID_TIMER);
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd,iMsg,wParam,lParam);
}