在面板中绘制一个动态椭圆

本文关键字:一个 动态 绘制 | 更新日期: 2023-09-27 18:19:45

我只想在运行时动态绘制一个椭圆。鼠标点击,然后鼠标移动,然后鼠标释放,就这样了。但是,对检测点(x,y)感到困惑。有人能帮我摆脱这个吗

在面板中绘制一个动态椭圆

您基本上只需要记录MouseDown事件的起点,这样您就可以用MouseUp事件记录的点制作椭圆。

简单演示:

public partial class Form1 : Form {
  private Point _StartPoint;
  private List<Rectangle> _Ovals = new List<Rectangle>();
  public Form1() {
    InitializeComponent();
    this.MouseDown += new MouseEventHandler(Form1_MouseDown);
    this.MouseUp += new MouseEventHandler(Form1_MouseUp);
    this.Paint += new PaintEventHandler(Form1_Paint);
  }
  void Form1_Paint(object sender, PaintEventArgs e) {
    foreach (Rectangle r in _Ovals)
      e.Graphics.FillEllipse(Brushes.Red, r);
  }
  void Form1_MouseDown(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left)
      _StartPoint = e.Location;
  }
  void Form1_MouseUp(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
      _Ovals.Add(MakeRectangle(_StartPoint, e.Location));
      this.Invalidate();
    }
  }
  private Rectangle MakeRectangle(Point p1, Point p2) {
    int x = (p1.X < p2.X ? p1.X : p2.X);
    int y = (p1.Y < p2.Y ? p1.Y : p2.Y);
    int w = Math.Abs(p1.X - p2.X);
    int h = Math.Abs(p1.Y - p2.Y);
    return new Rectangle(x, y, w, h);
  }
}