如何在vc++中旋转位图
2008-02-26 20:27:08 来源:WEB开发网第五步,实现位图旋转
我们假设旋转位图的函数原形如下:
void RotateBitmap(HDC dcSrc,int SrcWidth,int SrcHeight,double angle,HDC pDC);
/*参数解释如下://///////////////////////////////////////////////////////////////////////////
HDC dcSrc:要旋转的位图的内存设备环境,就是第四步创建的
int SrcWidth:要旋转位图的宽度
int SrcHeight:要旋转位图的高度
double angle:所要旋转的角度,以弧度为单位
HDC pDC:第三步得到的当前屏幕设备环境
*///////////////////////////////////////////////////////////////////////////////////////////////////////
//以下是函数实现细节
void RotateAnyAngle(HDC dcSrc,int SrcWidth,int SrcHeight,double angle)
{
double x1,x2,x3;
double y1,y2,y3;
double maxWidth,maxHeight,minWidth,minHeight;
double srcX,srcY;
double sinA,cosA;
double DstWidth;
double DstHeight;
HDC dcDst;//旋转后的内存设备环境
HBITMAP newBitmap;
sinA = sin(angle);
cosA = cos(angle);
x1 = -SrcHeight * sinA;
y1 = SrcHeight * cosA;
x2 = SrcWidth * cosA - SrcHeight * sinA;
y2 = SrcHeight * cosA + SrcWidth * sinA;
x3 = SrcWidth * cosA;
y3 = SrcWidth * sinA;
minWidth = x3>(x1>x2?x2:x1)?(x1>x2?x2:x1):x3;
minWidth = minWidth>0?0:minWidth;
minHeight = y3>(y1>y2?y2:y1)?(y1>y2?y2:y1):y3;
minHeight = minHeight>0?0:minHeight;
maxWidth = x3>(x1>x2?x1:x2)?x3:(x1>x2?x1:x2);
maxWidth = maxWidth>0?maxWidth:0;
maxHeight = y3>(y1>y2?y1:y2)?y3:(y1>y2?y1:y2);
maxHeight = maxHeight>0?maxHeight:0;
DstWidth = maxWidth - minWidth;
DstHeight = maxHeight - minHeight;
dcDst = CreateCompatibleDC(dcSrc);
newBitmap = CreateCompatibleBitmap(dcSrc,(int)DstWidth,(int)DstHeight);
SelectObject(dcDst,newBitmap);
for( int I = 0 ;I<DstHeight;I++)
{
for(int J = 0 ;J< DstWidth;J++)
{
srcX = (J + minWidth) * cosA + (I + minHeight) * sinA;
srcY = (I + minHeight) * cosA - (J + minWidth) * sinA;
if( (srcX >= 0) && (srcX <= SrcWidth) &&(srcY >= 0) && (srcY <= SrcHeight))
{
BitBlt(dcDst, J, I, 1, 1, dcSrc,(int)srcX, (int)srcY, SRCCOPY);
}
}
}
//显示旋转后的位图
BitBlt(hDC,200,200,(int)DstWidth,(int)DstHeight,dcDst,0,0,SRCCOPY);
DeleteObject(newBitmap);
DeleteDC(dcDst);
}
最后我们调用就可以了:
double angle = (45/180.0)*3.14159;//旋转45Degree,可为任意角度
RotateAnyAngle(dcSrc,bmpWidth,bmpHeight,angle,);
到这里就大功告成了.
更多精彩
赞助商链接