Question

I have a UserControl which overrides the OnRender-Method as follow:

MyUsercontrol.cs:

MyUserControl: UserControl
{
    protected override void OnRender(DrawingContext dc)
    {
       dc.DrawRectangle(Brushes.White, new Pen(Brushes.Black,1), new Rect(0,10,50,30));

       var visualBrush = new VisualBrush(new UserControl1{Height=30, Width=50});           
       dc.DrawGeometry(visualBrush, null, new RectangleGeometry(new Rect(50,10,50,30)));           
    }
}

The UserControl used above looks like this (defined in xaml, without additional codebehind code):

<UserControl x:Class="VisualBrushExample.UserControl1" ...>
<Grid>
   <Border BorderThickness="1" BorderBrush="Black" Background="White" CornerRadius=8,0,0,8"/>
</Grid>
</UserControl>

Now if I use MyUserControl I get following output:

example of created output with MyUserControl

My question now is, if there exists a way how I can use UserControl1 in the OnRender() method without get this transparent border around the UserControl1-Rectangle.

Thanks in advance, rhe1980

Was it helpful?

Solution

The reason that you see differently sized rectangle is simple. When you draw a rectangle with a Pen, the Pen line is centered on the rectangle's edges, or in other words the edge lies in the middle of the line. Therefore half of the Pen width lies outside the rectangle in each direction. Hence you have to add one Pen width to the rectangle's width and height to get the total size of the drawing output, 51 x 31 in your example.

You can perhaps check this by the Geometry.GetRenderBounds method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top