开发者

How do I get a WPF Canvas to put a TextBlock and Polygon in the same place?

How do I get a WPF Canvas object to render a TextBlock and a Polygon in the exact same position? I'm trying to overlay 2D labels onto a 3D scene, but while my Polygon backgrounds end in the right places, the TextBlocks don't...

You can see the results here.

(I know it'd be better to use Border objects instead of Polygons, but they don't position correctly either!)

Here's the code I'm using to try and do this:

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, mid开发者_运维百科dle.Y - 15);
    labelHolder.Children.Add(text);
}

I would be most grateful if you could help me get my Canvas under control, thank you!


Aha, the answer is that you need to specify Right and Top as well as Left and Bottom to make sure it's positioned exactly where you want it...

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);


Have you tried putting a grid where you want your polygon and then put your polygon and Textblock inside the grid? In a grid, items will overlap each other unless you stop them from doing so. In this case, you wouldn't want to stop them. You could even mess around with where your TextBox in relation to the walls of the grid so that it was where you wanted in over the polygon.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜