简体   繁体   English

如何在C#中的面板内绘制一个矩形?

[英]How can I draw a rectangle inside a panel in C#?

I want to draw a rectangle and I want to give position it with respect to the panel bottom. 我想画一个矩形,我想给它相对于面板底部的位置。

    public void populateTable(int x, int y)
    {
        using (Graphics g = this.CreateGraphics())
        {
            Brush b = new SolidBrush(Color.Red);
            g.FillRectangle(b, x, y, 100, 40);
        }

    }

When I execute the code above, the rectangle is created successfully. 当我执行上面的代码时,矩形成功创建。 But it's positioned with respect to form, not the panel. 但它的定位是关于形式,而不是面板。 If I put x=10, y=10, then it's shown in the upper left corner of the form. 如果我把x = 10,y = 10,那么它会显示在表格的左上角。 But I want to show it in the bottom where I put a panel. 但我想把它放在我放置面板的底部。

this.CreateGraphics() creates a Graphics object for this , which is the enclosing class - the form in this case. this.CreateGraphics() this创建一个Graphics对象,它是封闭类 - 在本例中为表单。

You should try panel1.CreateGraphics() instead. 你应该尝试使用panel1.CreateGraphics()

However, I would recommend not using CreateGraphics at all. 但是,我建议不要使用CreateGraphics It's better to handle OnPaint , so that your graphics gets redrawn when the form is redrawn (minimized then maximized, etc). 最好处理OnPaint ,以便在重绘表单时重新绘制图形(最小化然后最大化等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM