mayu789
mayu789

Reputation: 103

How to get exact measurement in WPF shapes

I am currently developing a simple drawing app in WPF. One of the feature in my app is to generate image of basic geometric shapes , from the user given measurements.

so i just tried to generate square with the width/height of 96 units. So for that i should get 1 inch (According to a device-independent unit (1/96th inch) ). But when i print my generated image its less than 1 inch ( side lenght is 2.22 cm)

I use below code to render the image.

RenderTargetBitmap rtb = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);

DrawingVisual dv = new DrawingVisual();

using (DrawingContext dc = dv.RenderOpen())
{
    VisualBrush vb = new VisualBrush(target);
    dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}

rtb.Render(dv);

Can anyone help me with this issue?

Upvotes: 0

Views: 565

Answers (2)

Mark A. Donohoe
Mark A. Donohoe

Reputation: 30328

Not sure why the other answers didn't just say to use 'Inches' as your units, or maybe it wasn't available back then, but that's the solution.

Here's an example to create a Canvas set to 8.5" x 11" to simulate a letter-sized piece of paper. It then adds three 1" squares in the top-left, top-right and bottom-right corners of the page, each with a one-inch margin from the edge of the 'paper'.

<Canvas x:Name="Paper"
    Width="8.5in" Height="11in"
    Background="White">

    <Rectangle Fill="Black"
        Width="1in" Height="1in"
        Canvas.Left="1in" Canvas.Top="1in" />

    <Rectangle Fill="Black"
        Width="1in" Height="1in"
        Canvas.Left="6.5in" Canvas.Top="1in" />

    <Rectangle Fill="Black"
        Width="1in" Height="1in"
        Canvas.Left="6.5in" Canvas.Top="9in" />

</Canvas>

If you then call this code, you can print it to see the results.

var printDialog = new PrintDialog();

if (printDialog.ShowDialog() == true) {
    printDialog.PrintVisual(Paper, "My First Print Job");
}

Upvotes: 0

Clemens
Clemens

Reputation: 128013

The following prints a rectangle on paper that is "exactly" 1x1 inch and positioned at 1 inch from the top left corner:

<Canvas x:Name="canvas">
    <Rectangle Stroke="Black" Width="96" Height="96" Canvas.Left="96" Canvas.Top="96"/>
</Canvas>

Code behind:

var pd = new PrintDialog();

if ((bool)pd.ShowDialog())
{
    pd.PrintVisual(canvas, "");
}

Upvotes: 1

Related Questions