在Inkcanvas C#WPF上的鼠标位置不绘制形状

时间:2014-04-11 11:31:56

标签: c# wpf visual-studio-2010 canvas

我使用以下代码在鼠标位置的墨迹上绘制正方形。但它不会在鼠标位置的中心绘制形状,而是略微向右和低得多,如下图所示:

enter image description here

另外,当我点击向画布添加形状时,我想停止画笔。

如何更正定位并停止绘图?

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

1 个答案:

答案 0 :(得分:1)

在您的代码中,这是指窗口?

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

如果是,则position是相对于窗口的光标位置而不是inkCanvas

尝试

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

如果要在选择工具时停止绘制画布,可以切换其IsEnabled属性。