2011-05-20 71 views
2

如何獲取WPF Canvas對象在完全相同的位置呈現TextBlock和Polygon?我想2D標籤覆蓋到3D場景,但同時我的多邊形背景在正確的地方結束,該的TextBlocks不...如何讓WPF Canvas將TextBlock和Polygon放在同一個地方?

You can see the results here.

(我知道這會是更好的使用邊界對象,而不是多邊形,但他們不正確的任一位置)

下面是我使用的嘗試做這樣的代碼:

foreach (Block block in blocks) 
{ 
    GeneralTransform3DTo2D transform = block.Top.TransformToAncestor(viewport); 
    GeometryModel3D model = block.Top.Content as GeometryModel3D; 
    MeshGeometry3D geometry = model.Geometry as MeshGeometry3D; 
    Point corner1 = transform.Transform(geometry.Positions[geometry.TriangleIndices[0]]); 
    Point corner2 = transform.Transform(geometry.Positions[geometry.TriangleIndices[1]]); 
    Point middle = new Point(corner1.X/2 + corner2.X/2, corner1.Y/2 + corner2.Y/2); 

    Polygon polygon = new Polygon(); 
    polygon.Stroke = Brushes.DimGray; 
    polygon.Fill = Brushes.LightGray; 
    polygon.Points.Add(new Point(middle.X - 15, middle.Y - 15)); 
    polygon.Points.Add(new Point(middle.X + 15, middle.Y - 15)); 
    polygon.Points.Add(new Point(middle.X + 15, middle.Y + 15)); 
    polygon.Points.Add(new Point(middle.X - 15, middle.Y + 15)); 
    labelHolder.Children.Add(polygon); 

    TextBlock text = new TextBlock(); 
    text.Text = block.Text; 
    text.Width = 30; 
    text.Height = 30; 
    text.TextAlignment = TextAlignment.Center; 
    text.FontSize = 11; 
    Canvas.SetLeft(text, middle.X - 15); 
    Canvas.SetBottom(text, middle.Y - 15); 
    labelHolder.Children.Add(text); 
} 

我將不勝感激,如果你能幫助我可以控制我的帆布,謝謝!

回答

2

啊哈,得到的答案是,你需要指定右和上以及左和底部,以確保它的準確定位,你想讓它...

Canvas.SetLeft(border, middle.X - border.Width/2); 
Canvas.SetRight(border, middle.X + border.Width/2); 
Canvas.SetBottom(border, middle.Y + border.Height/2); 
Canvas.SetTop(border, middle.Y - border.Height/2); 
0

你有沒有嘗試把網格放在你想要多邊形的地方,然後把你的多邊形和文本塊放入網格?在網格中,項目將互相重疊,除非您阻止它們這樣做。在這種情況下,你不想阻止他們。你甚至可以混淆TextBox與網格牆的相關位置,以便它可以在多邊形上的位置。

相關問題