【问题标题】:Shape not drawing at mouse position on inkcanvas C# WPF形状不在inkcanvas C# WPF上的鼠标位置绘制
【发布时间】:2014-04-11 11:31:55
【问题描述】:

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

此外,当我单击以向画布添加形状时,我想停止画笔。

如何纠正定位并停止画笔?

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

【问题讨论】:

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


    【解决方案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 属性。

    【讨论】:

    • 感谢第一部分工作,但禁用 inkcanvas 不允许我放置形状。
    • 或许禁用鼠标输入可以做到 IsHitTestVisible = false;
    • 我实际上用这个inkCanvas.EditingMode = InkCanvasEditingMode.None;解决了那个部分,谢谢你的意见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多