需求
希望image保持原有纵横比的前提下,希望image能够填充render window。当image的boundary不是正方形时,则以较长一边填充window。
效果图如下所是。
希望的效果图如下:
原理
VTK camera 主要有两种投影模式,一是透射投影,具有近大远小的效果;另一是正交投影,又叫平行投影。本篇文章只介绍平行投影情况,主要通过设置相机的parallel scale 进行设置。在VTK中,parallel scale作用在y方向,即图像的height,当image的height等于scale时,image高度方向刚好填充window的height。下面介绍几种场景。
- window 和viewport 均为正方形
viewport 刚好填充window,此时只需要设置scale的值为image高度的一半。 - window为正方形,viewport为矩形
当viewport的height > width 时,则设置scale为height的一半,此时高度方向填充,宽度方向则未填充。
当viewport的height < width 时,则设置scale为width的一半,此时宽度方向填充,高度方向未填充。 因为window是正方形,当viewport的height方向设置为width的大小,则宽度方向刚好填充viewport,高度方向空白区域被背景填充。 - 通用场景:window和viewport均为矩形
当image的宽高比小于window的宽高比时,则image相对更高,此时设置scale为image的height的一半。
当image的宽高比大于window的宽高比时,则image相对更宽,此时设置scale为image的宽除以window的宽高比的一半。目的是求出当image的宽填充时image的高是多少(这里的高包含上下填充的背景)。总而言之,要保持和window相同的比例,然后求解image的height,即 Wimage/Himage = Rwindow => Himage = Wimage / Rwindow,其中 Rwindow = Wwindow / Hwindow。由于image相对较矮,所以最终求出来的高无论如何都不会超出Window的Height。
code
double windowWidth = yourRenderWindow->GetSize()[0];
double windowHeight = yourRenderWindow->GetSize()[1];
// Assuming you have a reference to your scene's bounding box or extent
double sceneWidth = sceneBoundingBox->GetMax()[0] - sceneBoundingBox->GetMin()[0];
double sceneHeight = sceneBoundingBox->GetMax()[1] - sceneBoundingBox->GetMin()[1];
// Calculate the aspect ratios
double windowAspectRatio = windowWidth / windowHeight;
double sceneAspectRatio = sceneWidth / sceneHeight;
double parallelScale;
if (windowAspectRatio > sceneAspectRatio)
{
parallelScale = sceneHeight / 2.0;
}
else
{
parallelScale = (sceneWidth / windowAspectRatio) / 2.0;
}
Reference
[1] https://github.com/Kitware/glance/issues/230