C# 如何在影象上做(矩形/圓)標記
阿新 • • 發佈:2019-02-03
手動畫圓或橢圓
- private Point startPoint;
- private bool beginDragging;
- public Form1()
- {
- InitializeComponent();
- this.DoubleBuffered = true;
- }
- private void Form1_MouseMove(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left && beginDragging)
- {
- circle.Size = new Size(circle.Size.Width + e.X - startPoint.X, circle.Size.Height + e.Y - startPoint.Y);
- startPoint = new Point(e.X, e.Y);
- }
- this.Invalidate();
- }
- private void Form1_MouseDown(object sender, MouseEventArgs e)
- {
- if (e.Button
- {
- startPoint = e.Location;
- beginDragging = true;
- this.Capture = true;
- circle = new Circle();
- circle.Location = e.Location;
- Circles.Add(circle);
- this.Cursor = System.Windows.Forms.Cursors.Cross;
- }
- }
- private void Form1_MouseUp(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left && beginDragging)
- {
- beginDragging = false;
- this.Capture = false;
- this.Cursor = System.Windows.Forms.Cursors.Default;
- }
- this.Invalidate();
- }
- private void Form1_Paint(object sender, PaintEventArgs e)
- {
- Graphics g = e.Graphics;
- foreach (Circle each in Circles)
- {
- g.DrawEllipse(Pens.Black, new Rectangle(each.Location, each.Size));
- }
- }
- private List<Circle> Circles = new List<Circle>();
- private Circle circle = new Circle();
- public class Circle
- {
- public int Radii;
- public Size Size;
- public Point Location;
- }
自動畫圓
- //方法1
- private void button1_Click_1(object sender, EventArgs e)
- {
- Image im = new Bitmap(this.panel2.Width, this.panel2.Height);
- Graphics g = Graphics.FromImage(im);
- GraphicsPath gp = new GraphicsPath();
- Rectangle rec = new Rectangle(0, 0, 100, 100);
- gp.AddEllipse(rec);
- g.DrawEllipse(new Pen(Color.Red), rec);
- this.panel2.BackgroundImageLayout = ImageLayout.Stretch;
- this.panel2.BackgroundImage = im;
- }
- //方法2
- private void button3_Click(object sender, EventArgs e)
- {
- Graphics gra;
- Brush bush;
- gra = this.panel3.CreateGraphics();
- bush = new SolidBrush(Color.Red); //填充的顏色
- gra.FillEllipse(bush, 0, 0, 100, 100);//畫填充橢圓的方法,x座標、y座標、寬、高,如果是100,則半徑為50
- }
自動畫矩形
- //方法1
- private void button2_Click(object sender, EventArgs e)
- {
- Image im = new Bitmap(this.panel1.Width,this.panel1.Height);
- Graphics g = Graphics.FromImage(im);
- GraphicsPath gp = new GraphicsPath();
- Rectangle rec = new Rectangle(new Point(0,0),new Size(100,100));
- gp.AddRectangle(rec);
- g.DrawRectangle(new Pen(Color.Red), rec);
- this.panel1.BackgroundImageLayout = ImageLayout.Stretch;
- this.panel1.BackgroundImage = im;
- }
- //方法2
- private void button4_Click(object sender, EventArgs e)
- {
- Graphics gra;
- Brush bush;
- gra = this.panel4.CreateGraphics();
- bush = new SolidBrush(Color.Red);
- gra.DrawRectangle(new Pen(bush,20), 0, 0, 100, 100);
- }