QPixmap::scaled
是Qt中用于图像缩放的核⼼⽅法,其作⽤和⽤法如下:
一、核心作用
- 图像尺寸调整
根据指定尺寸对图像进⾏等⽐例或⾮等⽐例缩放,⽀持放⼤和缩⼩操作。 - 保持宽高比
通过AspectRatioMode
参数控制是否保持原始图像的宽⾼⽐。 - 渲染质量优化
提供快速变换(FastTransformation
)和平滑变换(SmoothTransformation
)两种模式,平衡性能与画质。
二、参数详解
1. 基本参数
cpp
QPixmap scaled(const QSize &size,
Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio,
Qt::TransformationMode transformMode = Qt::FastTransformation) const
- **
size
** :目标尺寸(QSize
或width, height
)。 - **
aspectRatioMode
** :宽⾼⽐控制模式,可选:Qt::IgnoreAspectRatio
:忽略宽⾼⽐,强制拉伸⾄目标尺寸。Qt::KeepAspectRatio
:保持宽⾼⽐,缩放到最⼤内接矩形。Qt::KeepAspectRatioByExpanding
:保持宽⾼⽐,缩放到最⼩外接矩形。
- **
transformMode
** :渲染质量模式:Qt::FastTransformation
:快速但可能有锯齿。Qt::SmoothTransformation
:平滑但性能开销较⼤。
2. 重载版本
cpp
QPixmap scaled(int width, int height, ...) // 直接指定宽高
三、典型用法示例
1. **等比例缩放(常用)**
cpp
QPixmap pixmap("image.png");
QPixmap scaled = pixmap.scaled(400, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- 保持原始宽⾼⽐,缩放到不超过400×300的最⼤尺寸。
2. 强制拉伸填充
cpp
pixmap.scaled(200, 200, Qt::IgnoreAspectRatio); // 可能变形
3. 高质量放大
cpp
pixmap.scaled(800, 600, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
四、应用场景
- 控件适配
在QLabel
中显示缩放后的图像时,通常结合setScaledContents(true)
使图像⾃适应控件⼤⼩。 - 性能优化
⼤图缩⼩时优先使⽤FastTransformation
,⼩图放⼤时推荐SmoothTransformation
。 - 动态交互
在⿏标滚轮缩放等交互场景中动态调⽤scaled
。
五、注意事项
- 内存管理:缩放会⽣成新图像,需避免频繁调⽤。
- SVG与PNG差异:SVG⽮量图缩放⽆失真,PNG位图可能失真。
- DPI适配 :⾼分辨率屏幕需结合
devicePixelRatio
调整。