0

这是我的代码,

        private bool isMouseOverPin(int x, int y, Pin pin)
    {
        int left, top, right, bottom,size;

        size=5;

        left = pin.theRectangle.Left-size;
        right = pin.theRectangle.Right + size;
        top = pin.theRectangle.Top - size;
        bottom = pin.theRectangle.Bottom + size;

        if (x >= left && y >= top && x <= right && y <= bottom)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void pinHover()
    {
        for (int i = 0; i < pins.Count; i++)
        {
            if (isMouseOverPin(Cursor.Position.X, Cursor.Position.Y, pins[i]) == true)
            {
                using (Graphics gr=canvas.CreateGraphics())
                {
                   gr.DrawRectangle(10,10,10,10);
                }
            }
        }
    }

    private void canvas_MouseMove(object sender, MouseEventArgs e)
    {
        pinHover();
    }

我想当有人将鼠标放在一个大头针上时,它会绘制一个矩形,大头针大小为 5,我无法理解为什么它不能正常工作。帮助请

4

1 回答 1

1

我怀疑您的引脚位置是相对于画布而不是相对于屏幕的。

您应该将 e.Location 从 MouseEventArgs 传递给 pinHover,或者您可以使用PointToClient

例如

    List<Int32> DrawPinRects;

    private void initBuffer()
    {
        DrawPinRects = new List<Int32>();
    }

    private void pinHover(Point Position)
    {
        DrawPinRects.Clear();
        for (int i = 0; i < pins.Count; i++)
        {
            if (isMouseOverPin(Position.X, Position.Y, pins[i]) == true)
            {
                DrawPinRects.Add(i);
            }
        }
    }

    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        pinHover(e.Location);
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        foreach(Int32 index in DrawPinRects)
        {
            Int32 y = panel1.VerticalScroll.Value + 10;
            e.Graphics.DrawRectangle(Pens.Black, 10, y, 10, 10);
        }
    }

还有这个:

    int left, top, right, bottom,size;

    size=5;

    left = pin.theRectangle.Left-size;
    right = pin.theRectangle.Right + size;
    top = pin.theRectangle.Top - size;
    bottom = pin.theRectangle.Bottom + size;

    if (x >= left && y >= top && x <= right && y <= bottom)

可以简化为

    int size = 5;

    Rectangle TestRect = pin.theRectangle;
    TestRect.Inflate(size,size);

    if (TestRect.Contains(x,y))

这将做同样的事情。

于 2012-10-25T13:24:32.490 回答