在下面代码中,我们使用VTK创建两个不同颜色渲染的三维长方体,可以使用鼠标进行拖动观察
一 代码
import vtk
import math
def main():
# 创建两个长方体数据源
cube1 = vtk.vtkCubeSource()
cube1.SetXLength(10)
cube1.SetYLength(2)
cube1.SetZLength(2)
cube2 = vtk.vtkCubeSource()
cube2.SetXLength(8)
cube2.SetYLength(2)
cube2.SetZLength(2)
# 创建映射器
cubeMapper1 = vtk.vtkPolyDataMapper()
cubeMapper1.SetInputConnection(cube1.GetOutputPort())
cubeMapper2 = vtk.vtkPolyDataMapper()
cubeMapper2.SetInputConnection(cube2.GetOutputPort())
# 创建actor
cubeActor1 = vtk.vtkActor()
cubeActor1.SetMapper(cubeMapper1)
cubeActor1.GetProperty().SetColor(1, 0, 0) # 红色
cubeActor2 = vtk.vtkActor()
cubeActor2.SetMapper(cubeMapper2)
cubeActor2.GetProperty().SetColor(0, 1, 0) # 绿色
# 创建变换
transform = vtk.vtkTransform()
transform.Translate(10, 0, 0) # 将第二个长方体沿x轴移动10个单位
transform.RotateY(30) # 将第二个长方体绕y轴旋转30度
transformFilter = vtk.vtkTransformPolyDataFilter()
transformFilter.SetInputConnection(cube2.GetOutputPort())
transformFilter.SetTransform(transform)
transformFilter.Update()
# 使用变换后的数据创建第二个长方体的映射器和actor
cubeMapper2Transformed = vtk.vtkPolyDataMapper()
cubeMapper2Transformed.SetInputConnection(transformFilter.GetOutputPort())
cubeActor2Transformed = vtk.vtkActor()
cubeActor2Transformed.SetMapper(cubeMapper2Transformed)
cubeActor2Transformed.GetProperty().SetColor(0, 1, 0) # 绿色,与原始actor相同
# 创建渲染器、渲染窗口和交互器
renderer = vtk.vtkRenderer()
renderer.AddActor(cubeActor1)
renderer.AddActor(cubeActor2Transformed)
renderer.SetBackground(0.1, 0.2, 0.4)
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(800, 600)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# 初始化并启动渲染循环
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == "__main__":
main()