调用矩形,简单的C#问题 [英] Calling a rectangle, simple c# question

查看:73
本文介绍了调用矩形,简单的C#问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 5);
Rectangle myRectangle = new Rectangle(20, 200, 40, 80);
graphicsObj.DrawRectangle(myPen, myRectangle);



我在名为draw1();的方法中创建了该矩形;
我有另一种方法叫做draw2(); ..
我怎样才能在draw1()中引用相同的矩形?改变它的背景色? (我知道如何更改背景颜色,我只需要在方法2中调用它即可.)就像实例化一样.



I created that rectangle in a method called draw1();
I have another method called draw2();..
How can I refer to that same rectangle in draw1(); to change it''s background colour? (I know how to change the background colour, I just need to call it in method 2).. Like an instantiation kind of thing.

推荐答案

不创建图形! (这是经验法则,但在99.90%的情况下有效.)
这个话题被讨论了很多次.始终使用Paint事件:

Do not create graphics! (This is a rule of thumb, but valid in 99.90% cases.)
This topic was discussed many times. Always use Paint event:

myControl.Paint += delegate(object sender, PaintEventArgs eventArgs) {
   using (Pen myPen = new Pen(System.Drawing.Color.Black, 5)) {
      Rectangle myRectangle = new Rectangle(20, 200, 40, 80);
      eventArgs.Graphics.DrawRectangle(myPen, myRectangle);
      DrawRectangleDetail(eventArgs.Graphics, myRectangle);
      DrawOnTopOfRectangle(eventArgs.Graphics, myRectangle);
      DrawSomethingElse(eventArgs.Graphics);
   } //using: here myPen.Dispose() is called automatically
}; //myControl.Paint



另外,您在哪里称呼myPen.Dispose?在上面的代码中显示了它:通过using构造(请参见注释).

现在,关于您的方法Draw1Draw2等.从上面显示的处理程序中全部调用它们.使它们接受Graphics参数,如果您需要重新使用已初始化的Rectange,请在需要的Rectangle中添加一个Rectangle参数.请参阅示例中对Draw...的调用.

—SA



Also, where do you call myPen.Dispose? In the code above it is shown: through the using construct (see comment).

Now, about your methods Draw1, Draw2, etc. Call them all from the handler show above. Make them accepting a Graphics parameter, if you need to re-use already initialized Rectange, add a Rectangle parameter to those which require that. See the calls to Draw... in my sample.

—SA


然后将矩形提升为成员变量而不是局部变量.

Then just promote your rectangle to a member variable instead of local variable.

Rectangle _rect = new Rectangle(20, 200, 40, 80);
void Draw1()
{
   //use _rect here...
}
void Draw2()
{
   //use _rect here...
}
//use this function to update your rectangle when needed
void UpdateRect()
{
   _rect = new Rectangle(...);
}


将method1的返回类型设置为 ^ ]

make the return type of method1 as Rectangle[^]

private Rectangle Draw1()
{
	Rectangle _myRect = null;
	//whatever
	return _myRect;
}



现在,您可以将其传递给method2进行更改.



Now you can pass it to the method2 to make changes there.

private void Draw2(Rectangle PobjRect)
{
    //whatever
}


这篇关于调用矩形,简单的C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆