crmepham
crmepham

Reputation: 4760

Shape not drawing at mouse position on inkcanvas C# WPF

I use the following code to draw a square on an inkcanvas at the position of the mouse. But it doesn't draw the shape at the centre of the mouse position, instead slightly to the right and much lower as demonstrated by the following image:

enter image description here

Additionally I would like to stop the pen from drawing when I click to add a shape to the canvas.

How can I correct the positioning and stop the pen drawing?

private void inkCanvas_MouseMove(object sender, MouseEventArgs e)
{
    cursorCoords.Content = Mouse.GetPosition(Application.Current.MainWindow);

    // Get the x and y coordinates of the mouse pointer.
    System.Windows.Point position = e.GetPosition(this);
    pX = position.X;
    pY = position.Y;
}

private Stroke NewRectangle(double dTop, double dLeft, double dWidth, double dHeight)
{
    double T = dTop;
    double L = dLeft;
    double W = dWidth;
    double H = dHeight;

    StylusPointCollection strokePoints = new StylusPointCollection();
    strokePoints.Add(new StylusPoint(L, T));
    strokePoints.Add(new StylusPoint(L + W, T));
    strokePoints.Add(new StylusPoint(L + W, T + H));
    strokePoints.Add(new StylusPoint(L, T + H));
    strokePoints.Add(new StylusPoint(L, T));

    Stroke newStroke = new Stroke(strokePoints);
    return newStroke;
}

private void inkCanvas_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (tool == 3) // shape tool
    {
        switch (chosenShape)
        {
            case "square":
                Stroke oS = NewRectangle(pY, pX, size, size);

                DrawingAttributes attribs = new DrawingAttributes();
                attribs.Color = shapeColour;//Colors.LimeGreen;
                attribs.Height = 5.0;
                attribs.Width = 5.0;
                attribs.FitToCurve = false;

                oS.DrawingAttributes = attribs;
                inkCanvas.Strokes.Add(oS);
                break;
        }
    }
}

Upvotes: 0

Views: 3358

Answers (1)

Dmitry
Dmitry

Reputation: 2062

In your code this refers to window?

// Get the x and y coordinates of the mouse pointer.
System.Windows.Point position = e.GetPosition(this);

If so then position is the cursor position relatively to the window and not to the inkCanvas

Try

System.Windows.Point position = e.GetPosition(inkCanvas);

If you want to stop canvas from drawing when you select a tool you can switch its IsEnabled property.

Upvotes: 1

Related Questions