public partial class Form1 : Form { static public Graphics lg; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); lg = e.Graphics; } public void test() { lg.DrawLine(ipen, point1,point2);//错误提示参数无效 Parameter is not valid. }} 1,我是这样传的,但不行, 2,pictureBox只有 pictureBox1_Paint,没有OnPaint,但是我想在pictureBox1上作图呀!
你这样使用e.Graphics是毫无意义的,这个graphics对象在OnPaint方法执行完毕后则被销毁了。所以你把他赋值给成员变量是没有用的。另外这个不叫全局,这是成员变量。封装、继承 LZ你没搞清楚啊,最好再多去琢磨下 class MyPictureBox:PictureBox { public Rectangle Rect { get; set; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; Pen p = new Pen(Color.Red,1); g.DrawRectangle(p,Rect); p.Dispose(); } }
按照面向对象编程的话,那么PictureBox的绘制应该在PictureBox内部最合理
我建议你将画的动作写在PictureBox的OnPaint()方法内,定义一个属性存储画图的数据(变量,如矩形长宽X,Y等),然后需要绘制时,外部先赋值该属性,然后调用PictureBox的Invalidate()重绘
public partial class Form1 : Form
{
static public Graphics lg; protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
lg = e.Graphics;
} public void test()
{
lg.DrawLine(ipen, point1,point2);//错误提示参数无效 Parameter is not valid.
}}
1,我是这样传的,但不行,
2,pictureBox只有 pictureBox1_Paint,没有OnPaint,但是我想在pictureBox1上作图呀!
class MyPictureBox:PictureBox
{
public Rectangle Rect { get; set; }
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Pen p = new Pen(Color.Red,1);
g.DrawRectangle(p,Rect);
p.Dispose();
}
}
2,函数结束e.Graphics销毁我也知道,
3,问题来了,也就是说我在外面无法作图了呢?
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
PaintSomething(e.Graphics); // 把Graphics参数传到画图的方法里
}// 这是具体画图的方法,可以在同一个类里,也可以在其它类或DLL里。
private void PaintSomething(Graphics g)
{
// 在这里画图
}