Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Qt 中用 scaled() 讓圖片自適應窗口大小

視頻類、拍照類應用都要顯示圖片,而用戶幾乎一定會去拖動窗口邊框。如果只把圖片畫上去、沒做自適應處理,窗口一放大,控件上就剩大片空白,體驗很差。

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 的目標尺寸,再把返回值重新繪製上去即可。

  1. void Widget::paintEvent(QPaintEvent *) 
  2. { 
  3.  
  4.     QImage img((unsigned char*)im.data,im.cols, 
  5.                    im.rows,QImage::Format_RGB888); 
  6.     QPainter painter(this); 
  7.     if(0==flag) 
  8.         painter.drawImage(0,0,nImg); 
  9.     /* 
  10.         一定要加標記位判斷,控件在繪制之前的size為NULL, 
  11.         所以scaled()返回值也為NULL,會提示nImg是空的 
  12.     */ 
  13.     else if(1==flag) 
  14.     { 
  15.         nImg=img.scaled(width(),height()); 
  16.         painter.drawImage(0,0,nImg); 
  17.     } 
  18. } 

這裡的 flag 判斷不能省。控件在首次繪製之前尺寸還是無效值,scaled 此時返回空圖,直接 drawImage 就會報 nImg 為空。

另外提醒兩點:默認參數是 IgnoreAspectRatio,會拉伸變形,想保持比例要傳 Qt::KeepAspectRatio;圖像是按比例縮放的,放大倍數過高必然模糊,必要時可改用 Qt::SmoothTransformation 換取更好的插值效果。

Copyright © Linux教程網 All Rights Reserved