Draw text on a shape in a wpf

2019-03-04 20:29发布

问题:

Some of you maybe find this question dull but I am still not deeply accustomed to wpf drawing. I want to add formatted text on a Rectangle which moves around on a canvas and I have got a hint to override the UIElement.OnRender method. However I do not know if I should override the canvas class or the Shape class. In any correct case, to what refers the drawingContext parameter of the method as described in the example: http://msdn.microsoft.com/en-us/library/bb613560.aspx#FormattedText_Object ?

Is the text ultimately assigned to the shape or is it a visual temporary effect that cannot move along with the shape on the canvas?

Is there any further effective means of drawing text on a shape?

回答1:

You can draw Text on top of a Rectangle by placing both controls in a parent container that allows controls to overlap, such as a Grid or a Canvas

<Grid>
    <Rectangle Fill="Red" Stroke="Black" 
               HorizontalAlignement="Stretch" VerticalAlignment="Stretch" />

    <Label Content="Test"
           HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

You can then apply whatever formatting you want to the Label, the Rectangle, and you can move the group around by setting the positioning of the Grid



回答2:

Rachel's answer is correct, although you can extend it a bit, have some UserControl defined as:

And in the codebehind define 1. Label:String DependencyProperty, Shape:UIElement DependencyProperty.

Handle the Shape's change event and call:

private void UpdateShape()
{
    grdShapeContainer.Children.Clear();
    if(this.Shape != null)
    {
        grdShapeContainer.Children.Add(this.Shape);
    }
}

This way you will be able to make things dynamic.

Regards, Artak



回答3:

You might also want to look into ZIndex property which can be set on objects like Grid (<Rectangle Background="Black" Grid.ZIndex = 99 /> for instance would put it overtop other items) which useful for making things like "loading" screens.



标签: c# wpf drawing