Skip to content

DistanceWidget

vtk-examples/Cxx/Widgets/DistanceWidget


Description

  • Contributed by Arnaud Gelas

Click two points to see the distance between them.

Other languages

See (Java)

Question

If you have a question about this example, please use the VTK Discourse Forum

Code

DistanceWidget.cxx

#include <vtkDistanceRepresentation.h>
#include <vtkDistanceWidget.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>

int main(int, char*[])
{
  vtkNew<vtkNamedColors> colors;

  // A renderer and render window
  vtkNew<vtkRenderer> renderer;
  vtkNew<vtkRenderWindow> renderWindow;
  renderWindow->AddRenderer(renderer);
  renderWindow->SetWindowName("DistanceWidget");

  renderer->SetBackground(colors->GetColor3d("Navy").GetData());

  // An interactor
  vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
  renderWindowInteractor->SetRenderWindow(renderWindow);

  vtkNew<vtkDistanceWidget> distanceWidget;
  distanceWidget->SetInteractor(renderWindowInteractor);
  distanceWidget->CreateDefaultRepresentation();
  static_cast<vtkDistanceRepresentation*>(distanceWidget->GetRepresentation())
      ->SetLabelFormat("%-#6.3g mm");

  // Render an image (lights and cameras are created automatically)
  renderWindow->Render();

  renderWindowInteractor->Initialize();
  renderWindow->Render();
  distanceWidget->On();

  // Begin mouse interaction
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(DistanceWidget)

find_package(VTK COMPONENTS 
  CommonColor
  CommonCore
  InteractionStyle
  InteractionWidgets
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
  QUIET
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "DistanceWidget: Unable to find the VTK build folder.")
endif()

# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(DistanceWidget MACOSX_BUNDLE DistanceWidget.cxx )
  target_link_libraries(DistanceWidget PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS DistanceWidget
  MODULES ${VTK_LIBRARIES}
)

Download and Build DistanceWidget

Click here to download DistanceWidget and its CMakeLists.txt file. Once the tarball DistanceWidget.tar has been downloaded and extracted,

cd DistanceWidget/build

If VTK is installed:

cmake ..

If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..

Build the project:

make

and run it:

./DistanceWidget

WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.