我需要一些关于从何处开始修改此程序的想法,以便当我点击picCanvas
(图片框)时,该位置会出现一个圆圈。到目前为止,该计划绘制了一个同心圆模式。
所有代码如下:
private Random randClick;
private Graphics paper;
private Brush bbrush;
private Pen pen;
private int circleSize = 30;
public Form1()
{
InitializeComponent();
randClick = new Random();
paper = picCanvas.CreateGraphics();
}
private void picCanvas_Click(object sender, EventArgs e)
{
int x, y;
x = picCanvas.Height / 2;
y = picCanvas.Width / 2;
Color color = Color.FromArgb(randClick.Next(0, 256), randClick.Next(0, 256), randClick.Next(0, 256));
Pen pen = new Pen(color);
pen.Width = 3;
circleSize += 10;
paper.DrawEllipse(pen, x - circleSize/2, y - circleSize/2, circleSize, circleSize);
}
答案 0 :(得分:2)
您需要使用MouseClick
偶数并使用X
的{{1}}和Y
属性来获取您点击的位置。
MouseEventArgs
答案 1 :(得分:2)
首先:您应该订阅MouseClick
活动而不是Click
- 这样您就可以访问提供的MouseEventArgs
中的鼠标位置和按钮。
第二件事:您尝试实现的方法可能不会持久 - 在最小化和恢复窗口后,DrawEllipse
将不再被调用。您必须向Paint
事件添加绘图方法。示例如下:
Point p = Point.Empty; // stores location of last mouseclick
bool clicked = false; // is picturebox clicked (if yes - circle should be drawn)
private void pictureBox1_MouseClick( object sender, MouseEventArgs e )
{
p = e.Location; // capture mouse click position
clicked = true; // notify the circle has to be drawn
pictureBox1.Refresh(); // force refresh of the control
}
private void pictureBox1_Paint( object sender, PaintEventArgs e )
{
// if there's a circle to be drawn
if ( clicked )
{
Graphics g = e.Graphics; // grab graphics object
g.DrawEllipse( Pens.Yellow, p.X - 4, p.Y - 4, 8, 8 ); // draw ellipse (a small one in this case)
}
}
答案 2 :(得分:1)
在List<>中存储每个圆圈的位置和颜色的信息。在班级。在这个例子中,我使用了一个元组,但你也可以使用自定义类。在Paint()事件中,您遍历List中的所有条目并呈现它们:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
picCanvas.Paint += new PaintEventHandler(picCanvas_Paint);
picCanvas.MouseDown += new MouseEventHandler(picCanvas_MouseDown);
}
private int circleSize = 30;
private Random R = new Random();
private List<Color> NamedColors = new List<Color>();
private List<Tuple<Point, Color>> Circles = new List<Tuple<Point, Color>>();
private void Form1_Load(object sender, EventArgs e)
{
foreach (Color C in System.ComponentModel.TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
{
if (C.IsNamedColor)
{
NamedColors.Add(C);
}
}
}
void picCanvas_MouseDown(object sender, MouseEventArgs e)
{
Tuple<Point, Color> circle = new Tuple<Point, Color>(
new Point(e.X, e.Y),
NamedColors[R.Next(NamedColors.Count)]);
Circles.Add(circle);
picCanvas.Invalidate();
}
void picCanvas_Paint(object sender, PaintEventArgs e)
{
foreach (Tuple<Point, Color> circle in Circles)
{
Rectangle rc = new Rectangle(circle.Item1, new Size(1, 1));
rc.Inflate(circleSize / 2, circleSize / 2);
using (Pen pen = new Pen(circle.Item2, 3))
{
e.Graphics.DrawEllipse(pen, rc);
}
}
}
}