自适应图片

 

有时我们在一个区域绘制一张图片,如果强制绘制,会失图片失真,所以自己写了一个简单算法,计算在当前区域下,按图片比例显示的区域为多大,居中
代码如下:

BOOL MeetRect(CRect &rc, CSize szPic)
{
 int x, y, w, h;
 int nWidth = rc.Width();
 int nHeight = rc.Height();

 if(nWidth > 0 && szPic.cx > 0)
 {
  // Get Meet Rect
  if(szPic.cx > nWidth || szPic.cy > nHeight)
  {
   const float fRatio = (float)nHeight / nWidth;
   const float fPicRatio = (float)szPic.cy / szPic.cx;

   if(fPicRatio > fRatio)
   {
    w = (int)(((float)nHeight) / fPicRatio);
    h = nHeight;
    x = rc.left + (nWidth - w) / 2;
    y = rc.top;   
   }
   else
   {
    w = nWidth;
    h = (int)(((float)nWidth )* fPicRatio);
    x = rc.left;
    y = rc.top + (nHeight - h) / 2;
   }
  }
  else
  {
   w = szPic.cx;
   h = szPic.cy;
   x = rc.left + (nWidth - w) / 2;
   y = rc.top + (nHeight - h) / 2;
  }

  rc.SetRect(x, y, x + w, y + h);
  return TRUE;
 }
 return FALSE;
}


 

原文地址:https://www.cnblogs.com/hgy413/p/3693594.html