QPixmap::scaled参数说明
QPixmap::scaled参数说明
QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const
官方文档给出参数解释
If aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap is scaled to size.
If aspectRatioMode is Qt::KeepAspectRatio, the pixmap is scaled to a rectangle as large as possible inside size, preserving the aspect ratio.
If aspectRatioMode is Qt::KeepAspectRatioByExpanding, the pixmap is scaled to a rectangle as small as possible outside size, preserving the aspect ratio.
对于aspectRatioMode
我们用图解和更具体的例子来解释 QPixmap::scaled()
函数中 aspectRatioMode
参数的三种模式。假设你有一张原始尺寸为 200x100 (宽x高) 的图片(宽:高 比例是 2:1),你想把它缩放到一个 150x150 的正方形区域 (size
)。
原始图片 (200x100):
+-------------------------+
| (宽 200) |
| | (高 100)
| |
+-------------------------+
目标区域 (150x150):
+---------------+
| |
| |
| | (150)
| |
| |
+---------------+(150)
现在看三种模式的效果:
-
Qt::IgnoreAspectRatio
(忽略宽高比)- 行为: 无论原始图片的宽高比是多少,都强制把它拉伸或压缩到你指定的确切尺寸 (150x150)。
- 结果尺寸: 150x150
- 视觉效果: 图片会被变形。因为原始是 2:1 的宽图,现在被硬塞进 1:1 的正方形,所以它会被垂直拉伸。
+---------------+ | | | | | 变形 | <- 图片被垂直拉伸填满整个 150x150 区域 | | | | +---------------+(150 x 150)
-
Qt::KeepAspectRatio
(保持宽高比)- 行为: 缩放图片,使其尽可能大,但必须完整地放入目标区域 (150x150) 内,同时保持原始图片的宽高比不变。
- 计算:
- 水平方向最大可以放大/缩小到 150 宽。
- 垂直方向最大可以放大/缩小到 150 高。
- 为了保持 2:1 的宽高比:
- 如果宽是 150,那么高应该是 150 / 2 = 75。
- 如果高是 150,那么宽应该是 150 * 2 = 300。
- 300 超过了 150 的宽度限制,不行。75 在 150 的高度限制内,可以。
- 所以最终尺寸是 150 (宽) x 75 (高)。
- 结果尺寸: 150x75
- 视觉效果: 图片不变形,完整显示,但会在目标区域内留下空白(上下各 37.5 像素的空白)。
+---------------+ | | <- 空白 (37.5px) +===============+ --- | | | | | | | 不变形,完整显示 | | 75px | | | | | | +===============+ --- | | <- 空白 (37.5px) +---------------+(150 px)
-
Qt::KeepAspectRatioByExpanding
(通过扩展保持宽高比)- 行为: 缩放图片,使其尽可能小,但必须完整地覆盖目标区域 (150x150),同时保持原始图片的宽高比不变。这意味着图片的某些部分可能会超出目标区域,需要裁剪。
- 计算:
- 水平方向至少需要 150 宽才能覆盖。
- 垂直方向至少需要 150 高才能覆盖。
- 为了保持 2:1 的宽高比:
- 如果宽是 150,那么高应该是 150 / 2 = 75。这不足以覆盖 150 高。
- 如果高是 150,那么宽应该是 150 * 2 = 300。这足以覆盖 150 宽。
- 为了满足“覆盖”的要求,我们必须让高度达到 150,因此宽度会变成 300。
- 所以最终尺寸是 300 (宽) x 150 (高)。
- 结果尺寸: 300x150
- 视觉效果: 图片不变形,完全覆盖了目标区域的高,但宽度超出了目标区域。你需要只显示中间 150x150 的部分,相当于裁剪掉了左右各 75px。
|<- 75px ->|<- 显示的 150px ->|<- 75px ->| +----------+-------------------+----------+ --- | | | | | | 裁剪 | | 裁剪 | | | 掉的 | 不变形,完全覆盖 | 掉的 | | 150px | 部分 | | 部分 | | | | | | | +----------+-------------------+----------+ --- (总宽 300px, 但只显示中间 150px)
核心区别总结:
IgnoreAspectRatio
: 强制缩放到指定大小,不管变形。KeepAspectRatio
: 完整显示图片,保持比例,但可能留有空白。KeepAspectRatioByExpanding
: 完全覆盖指定区域,保持比例,但可能需要裁剪。
对于transformMode
ConstantValueDescription
Qt::FastTransformation0The transformation is performed quickly, with no smoothing.
Qt::SmoothTransformation1The resulting image is transformed using bilinear filtering.
核心区别总结:
- 如果你需要最快的缩放速度,并且可以接受较低的图像质量,请选择
Qt::FastTransformation
。 - 如果你希望缩放后的图像看起来更平滑、质量更好,并且可以接受稍微慢一点的速度,请选择
Qt::SmoothTransformation
。在大多数用户界面应用中,推荐使用Qt::SmoothTransformation
。