需求:场景中一个actor,鼠标悬浮时 显示此actor的信息。
效果:
实现:
1,利用vtkInteractorStyleTrackballCamera 的OnMouseMove 事件 判断是否处于悬浮状态
2,判断悬浮后,首先将世界坐标转为屏幕坐标,然后分别绘制文字和背景,当不处于悬浮时,移除文字和背景。
//世界坐标 转屏幕坐标
double worldCoord[3] = {iter->second.x, iter->second.y, iter->second.z};
vtkSmartPointer<vtkCoordinate> pCoorPress = vtkSmartPointer<vtkCoordinate>::New();
pCoorPress->SetCoordinateSystemToWorld();
pCoorPress->SetValue(worldCoord);
int *dispCoord = pCoorPress->GetComputedDisplayValue(Renderer);
qDebug() << dispCoord[0] << dispCoord[1];
vtkNew<vtkNamedColors> colors;
//绘制文字
QString qstr = QString("x:%1 y:%2 z:%3").arg(iter->second.x).arg(iter->second.y).arg(iter->second.z);
vtkUnicodeString str = vtkUnicodeString ::from_utf8(qstr.toUtf8().data());
txtActor->SetInput(str.utf8_str());
vtkTextProperty* txtprop = txtActor->GetTextProperty();
txtprop->SetFontFamilyToArial();
//txtprop->BoldOn();
txtprop->SetFontSize(36);
txtprop->ShadowOn();
//txtprop->SetShadowOffse()
//背景
//获取文字宽高
double boundingBox[6];
txtActor->GetBoundingBox(Renderer, boundingBox);
double width = (boundingBox[1] - boundingBox[0])+20;
double height = (boundingBox[3] - boundingBox[2])+20;
vtkSmartPointer<vtkImageData> backgroundImage =
vtkSmartPointer<vtkImageData>::New();
backgroundImage->SetDimensions(width, height, 1);
backgroundImage->AllocateScalars(VTK_UNSIGNED_CHAR, 4);
unsigned char *pixels =
static_cast<unsigned char *>(backgroundImage->GetScalarPointer());
for (int i = 0; i < width * height * 1; ++i)
{
pixels[4 * i] = 172; // 红色分量
pixels[4 * i + 1] =0; // 绿色分量
pixels[4 * i + 2] = 0; // 蓝色分量
pixels[4 * i + 3] = 255;
}
vtkSmartPointer<vtkImageMapper> backgroundMapper =vtkSmartPointer<vtkImageMapper>::New();
backgroundMapper->SetInputData(backgroundImage);
backgroundActor->SetMapper(backgroundMapper);
backgroundActor->SetDisplayPosition(dispCoord[0]+_pointSize*4, dispCoord[1]-5);
Renderer->AddActor(backgroundActor);
ui->viewerWidget->update();