- class MyRubberBand : public vtkInteractorStyleRubberBand2D
- {
- public:
- static MyRubberBand* New();
- vtkTypeMacro(MyRubberBand, vtkInteractorStyleRubberBand2D);
- virtual void OnLeftButtonDown()
- {
- vtkInteractorStyleRubberBand2D::OnLeftButtonDown(); //必須有這一句
- startPosition[0] = this->GetInteractor()->GetEventPosition()[0];
- startPosition[1] = this->GetInteractor()->GetEventPosition()[1];
- startPosition[2] = 0;
- }
- virtual void OnLeftButtonUp()
- {
- vtkInteractorStyleRubberBand2D::OnLeftButtonUp(); //必須有這一句
- endPosition[0] = this->GetInteractor()->GetEventPosition()[0];
- endPosition[1] = this->GetInteractor()->GetEventPosition()[1];
- endPosition[2] = 0;
- std::cout<<"Position"<<endPosition[0]<<" "<<endPosition[1]<<std::endl;
- this->viewer->GetRenderer()->SetDisplayPoint(startPosition);
- this->viewer->GetRenderer()->DisplayToView();
- this->viewer->GetRenderer()->ViewToWorld();
- double start[4];
- this->viewer->GetRenderer()->GetWorldPoint(start);
- this->viewer->GetRenderer()->SetDisplayPoint(endPosition);
- this->viewer->GetRenderer()->DisplayToView();
- this->viewer->GetRenderer()->ViewToWorld();
- double end[4];
- this->viewer->GetRenderer()->GetWorldPoint(end);
- double point1[3];
- double point2[3];
- double point3[3];
- double point4[3];
- double left[2];
- double right[2];
- left[0] = start[0]<=end[0] ? start[0] : end[0];
- left[1] = start[1]<=end[1] ? start[1] : end[1];
- right[0] = start[0]>end[0] ? start[0] : end[0];
- right[1] = start[1]>end[1] ? start[1] : end[1];
- point1[0] = left[0]; point1[1] = left[1]; point1[2] = 0;
- point2[0] = left[0]; point2[1] = right[1]; point2[2] = 0;
- point3[0] = right[0]; point3[1] = right[1]; point3[2] = 0;
- point4[0] = right[0]; point4[1] = left[1]; point4[2] = 0;
- this->SetLine(point1,point2);
- this->SetLine(point2,point3);
- this->SetLine(point3,point4);
- this->SetLine(point4,point1);
- }
- void SetLine(double point1[],double point2[])
- {
- vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New();
- lineSource->SetPoint1(point1);
- lineSource->SetPoint2(point2);
- lineSource->Update();
- vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
- mapper->SetInputConnection(lineSource->GetOutputPort());
- vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
- actor->SetMapper(mapper);
- actor->GetProperty()->SetLineWidth(2);
- actor->GetProperty()->SetColor(1.0,0.0,0.0);
- this->viewer->GetRenderer()->AddActor(actor);
- this->viewer->Render();
- }
- vtkImageViewer2* viewer;
- //
- private:
- double startPosition[3];
- double endPosition[3];
- };
要點:app
1.在從新實現的onLeftButtonDown()函數中,必須調用 vtkInteractorStyleRubberBand2D::OnLeftButtonDown(); 不然沒法交互;onLeftButtonUp()函數同理;ide
2.經過 this->GetInteractor()->GetEventPosition()獲得的是屏幕座標,必須先將其轉換成世界座標,不然矩形位置並不正確;函數
3.viewer->SetupInteractor(iren)必須置於iren->SetInteractorStyle(style)以前,否者viewer還使用原來的InteractorStyle。this