方法一:直接使用WorldToDisplay函数转换
int x = 110, y = 176, z = 107;
double view3[3];
renderer->SetWorldPoint(x, y, z, 1);//输入待换算三维点坐标
renderer->WorldToDisplay();//执行坐标变换
renderer->GetDisplayPoint(view3);//读取变换结果,u=view[0] v=view[1]
方法二:如果有大量点需要转换可以使用GetCompositeProjectionTransformMatrix获得投影变换矩阵,然后计算点在屏幕上的投影位置。
参数GetTiledAspectRatio()
表示渲染窗口的长宽比,这个参数通常设置为1.0,0
和2
是默认参数值,表示使用默认的near和far剪裁平面。
float testpoint[4]{ x, y, z, 1 };
float* view4;
vtkMatrix4x4* matrix = ren->GetActiveCamera()->GetCompositeProjectionTransformMatrix(ren->GetTiledAspectRatio(), 0, 2);
view4 = matrix->MultiplyPoint(testpoint);
if (view4[3] != 0)
{
view4[0] /= view4[3];
view4[1] /= view4[3];
view4[2] /= view4[3];
}
int u = (view4[0] + 1.0) * _windowWidth / 2;//_windowWidth为RenderWindow的宽度
int v = (view4[1] + 1.0) * _windowHeight / 2;
view4[0] + 1的原因为x_world和y_world的范围是[-1,1],那么将它们加1之后,范围就变成了[0,2],然后再除以2,就可以将范围归一化到[0,1]。