Qt兑现图像自适应窗口大小之scaled()函数使用
Qt实现图像自适应窗口大小之scaled()函数使用
很多应用都需要显示图片,比如视频类应用、拍照类应用,但是在大数情况下用户都会改变窗口大小,
以获得最佳效果,在Qt中如果只设置了显示图片而没有对自适应窗口做出设置,用户拖拽边框的时候,
整个控件上就会出现大片空白部分,怎么解决这个问题呢?
QImage、QPixmap等绘图设备类都提供scaled()函数,下面是Qt文档对于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()的返回重新进行绘图即可自适应窗口,以下是个例子:
void Widget::paintEvent(QPaintEvent *) { QImage img((unsigned char*)im.data,im.cols, im.rows,QImage::Format_RGB888); QPainter painter(this); if(0==flag) painter.drawImage(0,0,nImg); /* 一定要加标记位判断,控件在绘制之前的size为NULL, 所以scaled()返回值也为NULL,会提示nImg是空的 */ else if(1==flag) { nImg=img.scaled(width(),height()); painter.drawImage(0,0,nImg); } }
Ps:
图像是按比例变化的,如果放大很多,会出现模糊等现象