MFC下对位图的旋转

来源:互联网 发布:yy淘宝互刷平台 编辑:程序博客网 时间:2024/06/08 10:56

          开始做一个项目,需要在MFC下旋转一个位图。遍寻网上各种资源,把代码copy下来发现不能用,悲催至极。

          还有就是网上给出的很多代码本身有很多变量和项目工程有关,有关变量不够明确。因此决定自己写这样一个旋转函数,函数实现功能:输入位图类和旋转角,返回一个和原图大小一样经过旋转之后的位图。(当然此处因为我只关心中心部分的旋转,而且并不会丢失,因此不考虑边缘位置。 当然如果希望返回一个更大的包含完整信息的图片,可以对代码进行稍加修改即可)

          关于旋转的原理,通过坐标变换。这个我就不解释了.

          下面具体的代码:

//将一幅图片转换角度后返回新的图片CBitmap*BmpRotate(CBitmap*cBmp, float Angle){ BITMAP bmp; cBmp->GetBitmap(&bmp); BYTE *pBits = new BYTE[bmp.bmWidthBytes*bmp.bmHeight], *TempBits = new BYTE[bmp.bmWidthBytes*bmp.bmHeight]; cBmp->GetBitmapBits(bmp.bmWidthBytes*bmp.bmHeight, pBits); Angle = Angle*3.1415926 / 180; int interval=bmp.bmWidthBytes/bmp.bmWidth; double rx0 = bmp.bmWidth*0.5; double ry0 = bmp.bmHeight*0.5;  for (int j = 0; j < bmp.bmHeight; j ++) {  for (int i = 0; i < bmp.bmWidth; i++)  {   for (int k = 0; k < interval; k++)   {    TempBits[i*bmp.bmWidthBytes + j*interval + k] = 0xff;   }  } } for (int j = 0; j < bmp.bmHeight; j++) {  for (int i = 0; i< bmp.bmWidth; i++)  {      int tempI, tempJ;   tempI = (i-rx0)*cos(Angle) + (j-ry0)*sin(Angle)+rx0;   tempJ = -(i-rx0)*sin(Angle) + (j-ry0)*cos(Angle)+ry0;   if (tempI>0&&tempI<bmp.bmWidth)    if (tempJ>0 && tempJ < bmp.bmHeight)    {    for (int m = 0; m < interval;m++)     TempBits[i*bmp.bmWidthBytes + j*interval+m] = pBits[tempI*bmp.bmWidthBytes + interval*tempJ+m];    }
  } } CBitmap *m_bitmap; m_bitmap = new CBitmap; m_bitmap->CreateBitmapIndirect(&bmp); m_bitmap->SetBitmapBits(bmp.bmWidthBytes*bmp.bmHeight, TempBits); delete pBits; delete TempBits; return m_bitmap;}




0 0