《Windows程序设计》之BOUNCE

简单动画的实现


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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值