1、函數
// 功能: 矩形區縮放到目標矩形區
// 參數:
// rcDest : 目標矩形區域
// nSrcWidth: 被縮放矩形區的寬度
// nFormat: 矩形區在目標矩形區對齊方式 DT_TOP DT_VCENTER DT_BOTTOM DT_LEFT DT_CENTER DT_RIGHT
// 返回值: 矩形區縮放后在目標矩形區的位置
//#define DT_TOP 0x00000000 // 垂直方向頂端對齊
//#define DT_LEFT 0x00000000 // 水平方向左對齊
//#define DT_CENTER 0x00000001 // 水平方向居中對齊
//#define DT_RIGHT 0x00000002 // 水平方向右對齊
//#define DT_VCENTER 0x00000004 // 垂直方向居中對齊
//#define DT_BOTTOM 0x00000008 // 垂直方向底部對齊
CRect Zoom(CRect rcDest, int nSrcWidth, int nSrcHeight, UINT nFormat)
{
float fW = 1.0 * nSrcWidth / rcDest.Width();
float fH = 1.0 * nSrcHeight / rcDest.Height();
float fRatio = fW;
if ( fH - fW > 0.000001 && fH - 1 > 0.00001 )
fRatio = fH;
nSrcWidth *= fRatio;
nSrcHeight*= fRatio;
CRect rc;
if ( 0 == nFormat )
{
rc.top = rcDest.top;
rc.bottom = rc.top + nSrcHeight;
}
else if ( 0 != nFormat&0x00000001 )
{
rc.top = rcDest.top + (rcDest.Height() - nSrcHeight)/2;
rc.bottom = rc.top + nSrcHeight;
}
else if ( 0 != nFormat&0x00000008 )
{
rc.bottom = rcDest.bottom;
rc.top = rc.bottom - nSrcHeight;
}
if ( 0 == nFormat )
{
rc.left = rcDest.left;
rc.right= rc.left + nSrcWidth;
}
else if ( 0 != nFormat&0x00000001 )
{
rc.left = rcDest.left + (rcDest.Width()-nSrcWidth)/2;
rc.right= rc.left + nSrcWidth;
}
else if ( 0 != nFormat&0x00000002 )
{
rc.right = rcDest.right;
rc.left = rc.right - nSrcWidth;
}
return rc;
}
2、使用示例
例如將一張300*200的位圖縮放到CRect(100, 50, 500, 300)區域中,並且位圖在目標區域中垂直與水平方向都居中對齊
CRect rc = Zoom(CRect(100, 50, 500, 300), 300,200, DT_VCENTER | DT_CENTER);