鼠标移动时重绘图形路径

本文关键字:图形 路径 绘图 移动 鼠标 | 更新日期: 2024-11-06 08:11:27

我使用 Graphics Path OnPaintEvent 绘制了圆形矩形并且我已经添加了鼠标事件以了解光标是否在g.p上。

void Round_MouseMove(object sender, MouseEventArgs e)
        {
          Point mousePt = new Point(e.X, e.Y);
          if (_path != null)
             if (_path.IsVisible(e.Location))
                MessageBox.Show("GraphicsPath has been hovered!");
        }

问题:有没有办法调整大小或重绘(隐藏上一个然后绘制新的)图形路径运行时?

鼠标移动时重绘图形路径

调用Invalidate来重绘Form,因此OnPaint(PaintEventArgs e)将被执行。

检查以下示例:

public sealed partial class GraphicsPathForm : Form
{
    private bool _graphicsPathIsVisible;
    private readonly Pen _pen = new Pen(Color.Red, 2);
    private readonly Brush _brush = new SolidBrush(Color.FromArgb(249, 214, 214));
    private readonly GraphicsPath _graphicsPath = new GraphicsPath();
    private Rectangle _rectangle = new Rectangle(10, 30, 100, 100);
    public GraphicsPathForm()
    {
        InitializeComponent();
        _graphicsPath.AddRectangle(_rectangle);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        var g = e.Graphics;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.InterpolationMode = InterpolationMode.Bilinear;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.DrawPath(_pen, _graphicsPath);
        if (_graphicsPathIsVisible)
            g.FillPath(_brush, _graphicsPath);

        base.OnPaint(e);
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
        var isVisible = _graphicsPath.IsVisible(e.Location);
        if (isVisible == _graphicsPathIsVisible)
            return;
        const int zoom = 5;
        if (isVisible)
        {
            if (!_graphicsPathIsVisible)
            {
                _rectangle.Inflate(zoom, zoom);
                _graphicsPath.Reset();
                _graphicsPath.AddRectangle(_rectangle);
            }
        }
        else
        {
            if (_graphicsPathIsVisible)
            {
                _rectangle.Inflate(-zoom, -zoom);
                _graphicsPath.Reset();
                _graphicsPath.AddRectangle(_rectangle);
            }
        }
        _graphicsPathIsVisible = isVisible;
        Invalidate();
        base.OnMouseMove(e);
    }
}

我希望它有所帮助。