C++ Qt:如何调整图像大小并保持其比例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19715232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt: How do I resize an image and maintain its proportions?
提问by Pietro
This Qt exampleshows how to resize an image contained in a dialog, so that when the dialog is resized, the image stretches accordingly.
这个 Qt示例显示了如何调整对话框中包含的图像的大小,以便在调整对话框大小时,图像会相应地拉伸。
How can I resize an image in the same way, without distorting it / keeping its proportions the same?
如何以相同的方式调整图像大小,而不会扭曲它/保持其比例不变?
Of course if the width/height ratio of the dialog is different from the one of the image, I will get a "grey" area.
I found the Qt::KeepAspectRatio
enum, but not the function to use it with.
当然,如果对话框的宽高比与图像不同,我会得到一个“灰色”区域。
我找到了Qt::KeepAspectRatio
枚举,但没有找到使用它的函数。
Update: This is the code I am trying with:
更新:这是我正在尝试的代码:
QImage image(path);
QImage image2 = image.scaled(200, 200, Qt::KeepAspectRatio);
QLabel *plotImg = new QLabel;
plotImg->setScaledContents(true);
plotImg->setPixmap(QPixmap::fromImage(image2));
The image does not maintain a constant aspect ratio when the label is resized. And it looses resolution after the rescaling.
调整标签大小时,图像不会保持恒定的纵横比。并且在重新缩放后它会失去分辨率。
回答by Guilherme Bernal
Use the QImage::scaled
function.
使用该QImage::scaled
功能。
QImage img("someimage.png");
QImage img2 = img.scaled(100, 100, Qt::KeepAspectRatio);
In case you need it for QPixmap
, a function with the same name exists.
如果您需要它QPixmap
,则存在同名的函数。