首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC++

VC++ 圖像等比例縮放算法:保持長寬比的最佳顯示矩形計算

     編輯:VC++

問題描述

在目標矩形區域 (如螢幕、打印頁、控件客戶區) 內顯示圖片,需保持原始長寬比,最大化填充且不變形,可選居中。

算法核心邏輯

  1. 計算目標區域寬高比 targetRatio = targetW / targetH。
  2. 計算圖片寬高比 imgRatio = imgW / imgH。
  3. 比較兩比值:
    • imgRatio > targetRatio:圖片相對更「寬」,以目標寬度為基準縮放,高度留白 (上下居中)。
    • imgRatio < targetRatio:圖片相對更「高」,以目標高度為基準縮放,寬度留白 (左右居中)。
    • 相等:完美填充。
  4. 返回縮放後的目標矩形 (含偏移量)。

函數實現

CRect RectSizeWithConstantRatio(const CRect* pTargetRect, CSize imgSize, BOOL bCenter) {
    CRect rect(*pTargetRect);
    double targetW = rect.Width(), targetH = rect.Height();
    double targetRatio = targetW / targetH;
    double imgW = imgSize.cx, imgH = imgSize.cy;
    double imgRatio = imgW / imgH;

    if (imgRatio > targetRatio) {
        // 寬度受限
        int newH = (int)(targetW / imgW * imgH);
        int offsetY = bCenter ? (rect.Height() - newH) / 2 : 0;
        rect.SetRect(0, offsetY, (int)targetW, offsetY + newH);
    } else if (imgRatio < targetRatio) {
        // 高度受限
        int newW = (int)(targetH / imgH * imgW);
        int offsetX = bCenter ? (rect.Width() - newW) / 2 : 0;
        rect.SetRect(offsetX, 0, offsetX + newW, (int)targetH);
    }
    // 相等時 rect 保持原樣 (滿屏)
    return rect;
}

調用示例

// 獲取螢幕尺寸
CRect screenRect(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
// 圖片尺寸 (假設從 IPicture 或文件頭獲取)
CSize imgSize(picture.m_Width, picture.m_Height);

// 計算最佳顯示矩形 (居中)
CRect drawRect = RectSizeWithConstantRatio(&screenRect, imgSize, TRUE);

// 繪制
picture.Render(dc.m_hDC, drawRect.left, drawRect.top, drawRect.Width(), drawRect.Height(), ...);

擴展建議

  • 增加 StretchMode 參數:FIT_INSIDE (內部適配,留白)、COVER (覆蓋,裁剪)、FILL (拉伸填充,變形)。
  • 支援高 DPI:傳入邏輯坐標並根據 DPI 縮放因子換算。
  • 整合到 CPictureEx 等圖片類作為成員方法。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved