如何通过点击按钮在面板上绘制东西
问题描述:
我有一个面板和一个按钮。即:如何通过点击按钮在面板上绘制东西
private void button1_Click(object sender, EventArgs e)
{
panel2.Paint += new PaintEventHandler(panel2_Paint);
panel2.Refresh();
}
和:
private void panel2_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
Graphics[,] g1 = new Graphics[140, 140];
int[,] graph = new int[140, 140];
int i, j;
for (i = 0; i < 140; i++)
for (j = 0; j < 140; j++)
{
graph[i, 8] = 1;
graph[i, 10] = 1;
}
Pen p = new Pen(Color.Blue);
SolidBrush mySolidColorBrush = new SolidBrush(Color.Blue);
Graphics a;
a = this.CreateGraphics();
for (i = 1; i <= 10; i++)
for (j = 1; j <= 14; j++)
{
g.DrawEllipse(p, 80 * i, 80 * j, 10, 10);
g.FillEllipse(mySolidColorBrush, 80 * i, 80 * j, 20, 20);
a.DrawLine(Pens.Blue, 80 * i, 80 * j, 80 * (i - 1), 80 * (j - 1));
}
}
当我点击按钮的输出应显示面板上,但我的情况下,它会显示在表格。
答
您应该创建自己的用户控件来完成绘图任务。
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public void DrawStuff()
{
this.Paint += new PaintEventHandler(panel1_Paint);
this.Refresh();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Graphics[,] g1 = new Graphics[140, 140];
int[,] graph = new int[140, 140];
int i, j;
for (i = 0; i < 140; i++)
for (j = 0; j < 140; j++)
{
graph[i, 8] = 1;
graph[i, 10] = 1;
}
Pen p = new Pen(Color.Blue);
SolidBrush mySolidColorBrush = new SolidBrush(Color.Blue);
Graphics a;
a = this.CreateGraphics();
for (i = 1; i <= 10; i++)
for (j = 1; j <= 14; j++)
{
g.DrawEllipse(p, 80 * i, 80 * j, 10, 10);
g.FillEllipse(mySolidColorBrush, 80 * i, 80 * j, 20, 20);
a.DrawLine(Pens.Blue, 80 * i, 80 * j, 80 * (i - 1), 80 * (j - 1));
}
}
}
然后,你可以从父控件调用公共方法绘制东西。
private void button1_Click(object sender, EventArgs e)
{
userControl11.DrawStuff();
}
这是你可以通过自己创建自定义控制。检查视频https://www.youtube.com/watch?v=l5L_q_jI494 –
userControl11.DrawStuff(); 这里usercontrol1不是一个对象,所以用这个 –
来调用一个函数是无效的。你需要做的步骤是:1.创建一个新的UserControl(即UserControl1)2.将这两个方法添加到新的控件中3.编译你的解决方案4.将新UserControl1拖到您的UI中5.从Button –