視頻類、拍照類應用都要顯示圖片,而用戶幾乎一定會去拖動窗口邊框。如果只把圖片畫上去、沒做自適應處理,窗口一放大,控件上就剩大片空白,體驗很差。
QImage、QPixmap 等繪圖設備都提供 scaled() 函數,先看官方文檔:
函數原型:
QImage QImage::scaled ( int width, int height,
Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio,
Qt::TransformationMode transformMode = Qt::FastTransformation ) const
This is an overloaded function.
Returns a copy of the image scaled to a rectangle with the given width and height according to the given aspectRatioMode and transformMode.
If either the width or the height is zero or negative, this function returns a null image.
翻譯過來就是:這是一個重載函數,按給定的寬高,依據縱橫比模式與轉換模式返回縮放後的副本;寬或高為 0 或負數時返回空圖像。
所以思路很簡單:拿到控件變化後的寬高,用它作為 scaled 的目標尺寸,再把返回值重新繪製上去即可。
這裡的 flag 判斷不能省。控件在首次繪製之前尺寸還是無效值,scaled 此時返回空圖,直接 drawImage 就會報 nImg 為空。
另外提醒兩點:默認參數是 IgnoreAspectRatio,會拉伸變形,想保持比例要傳 Qt::KeepAspectRatio;圖像是按比例縮放的,放大倍數過高必然模糊,必要時可改用 Qt::SmoothTransformation 換取更好的插值效果。