我在WinForms Application C#中有一个用于图像分割的程序,我在pictureBox中加载了一个图像。我需要在该图像上绘制一个小圆圈(或椭圆,无关紧要)(在感兴趣的区域内,并允许它向外生长,直到达到所需的边界)。
问题是如何在该图像的任何位置绘制该圆圈? (如果可以用不同的颜色绘制那个圆圈,例如红色)
谢谢。
答案 0 :(得分:2)
当然可以使用控件的图形实例并在其上绘制。只有在重新绘制或无效时才会反映出来。使用Graphic Class的DrawEllipse Method绘制圆圈。
这是代码:
Graphics gf = picturebox1.CreateGraphics();
//A circle with Red Color and 2 Pixel wide line
gf.DrawEllipse(new Pen(Color.Red, 2),new Rectangle(0, 0, 200, 200));
使其无效以在控件(图片框)上实际绘制它
picturebox1.Invalidate();
它将绘制一个直径为200像素的圆
答案 1 :(得分:2)
参考: @Albin在draw-an-arrow-on-a-picturebox
处回答public partial class Form1 : Form
{
private bool isMoving = false;
private Point mouseDownPosition = Point.Empty;
private Point mouseMovePosition = Point.Empty;
private Dictionary<Point, Point> Circles = new Dictionary<Point, Point>();
public Form1()
{
InitializeComponent();
//
// pictureBox1
//
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(231, 235);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
this.Controls.Add(this.pictureBox1);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Pen p = new Pen(Color.Red);
var g = e.Graphics;
if (isMoving)
{
g.Clear(pictureBox1.BackColor);
g.DrawEllipse(p, new Rectangle(mouseDownPosition, new Size(mouseMovePosition.X - mouseDownPosition.X, mouseMovePosition.Y - mouseDownPosition.Y)));
foreach (var circle in Circles)
{
g.DrawEllipse(p, new Rectangle(circle.Key, new Size(circle.Value.X - circle.Key.X, circle.Value.Y - circle.Key.Y)));
}
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
pictureBox1.Cursor = Cursors.Cross;
isMoving = true;
mouseDownPosition = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isMoving)
{
mouseMovePosition = e.Location;
pictureBox1.Invalidate();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
pictureBox1.Cursor = Cursors.Default;
if (isMoving)
{
Circles.Add(mouseDownPosition, mouseMovePosition);
}
isMoving = false;
}
}