原例子用了复杂的图形,我这边改成简单的cylinder,注意点击图形后再按p进入pick模式就可以显示鼠标点pick的信息了。如果不点击图形,会先报错”no current renderer on the interactor style.“,不过忽略后之后依然正常显示pick信息。
//pick.cpp
#include "Pick.h"
#include "vtkCellPicker.h"
#include "vtkCommand.h"
#include "vtkTextMapper.h"
#include "vtkTextProperty.h"
#include "vtkActor2D.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "Cylinder.h"
#include "vtkInteractorObserver.h"
#include "vtkCallbackCommand.h"
vtkActor2D* textActor;
vtkTextMapper* textMapper;
vtkRenderWindow* renWin;
class AnnotatePick : public vtkCommand
{
public:
static AnnotatePick* New()
{
return new AnnotatePick();
}
virtual void Execute(vtkObject* caller, unsigned long eventID, void* callData)
{
//vtkCellPicker* picker = reinterpret_cast<vtkCellPicker*>(caller);
vtkCellPicker* picker = vtkCellPicker::SafeDownCast(caller);
if (!picker)
{
return;
}
if (picker->GetCellId() < 0)
{
textActor->VisibilityOff();
}
else
{
double* selPt = picker->GetSelectionPoint();
double x = selPt[0];
double y = selPt[1];
auto pickPos = picker->GetPickPosition();
double xp = pickPos[0];
double yp = pickPos[1];
double zp = pickPos[2];
char s[256];
sprintf_s(s, sizeof(s), "xp:%f, yp:%f, zp:%f", xp, yp, zp);
textMapper->SetInput(s);
textActor->SetPosition(x, y);
textActor->VisibilityOn();
}
renWin->Render();
}
};
Pick::Pick()
{
//picker
vtkCellPicker* picker = vtkCellPicker::New();
AnnotatePick* annotatePick = AnnotatePick::New();
picker->AddObserver(vtkCommand::EndPickEvent, annotatePick);
annotatePick->Delete();
//文字显示设置
textMapper = vtkTextMapper::New();
auto tprop = textMapper->GetTextProperty();
tprop->SetFontFamilyToArial();
tprop->SetFontSize(10);
tprop->BoldOn();
tprop->ShadowOn();
tprop->SetColor(1, 0, 0);
textActor = vtkActor2D::New();
textActor->VisibilityOff();
textActor->SetMapper(textMapper);
//窗口相关设置
vtkRenderer* ren = vtkRenderer::New();
renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren);
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
iren->SetPicker(picker);
//
auto cylinderActor = Cylinder::getActor();
ren->AddActor2D(textActor);//注意是AddActor2D
ren->AddActor(cylinderActor);//两个Actor要加到一个renderer里否则文字不显示
renWin->Render();
//
picker->Pick(85, 126, 0, ren);//模拟pick
iren->Start();
}
//Cylinder.cpp
#include "Cylinder.h"
vtkActor* Cylinder::getActor()
{
vtkCylinderSource* cylinder = vtkCylinderSource::New();
vtkPolyDataMapper* cylinderMapper = vtkPolyDataMapper::New();
cylinderMapper->SetInputConnection(cylinder->GetOutputPort());
vtkActor* cylinderActor = vtkActor::New();
cylinderActor->SetMapper(cylinderMapper);
return cylinderActor;
}
#include "Pick.h"
VTK_MODULE_INIT(vtkRenderingFreeType);
int main()
{
Pick c;
}
头文件很简单我就不再赘述。