C# Drawing in a Panel

2019-08-28 20:56发布

I want to draw in a panel with this method:

protected override void InitOutput(object output)
        {
            if (output is Control)
            {
                Control c = (Control)output;
                g.FillRectangle(hb, 7, 10, 30 - 19, 5);
                ...
            }

With a text I can do this:

protected override void InitOutput(object output)
        {
            if (output is Control)
            {
                Control c = (Control)output;
                lbl.Name = "lbl";
                lbl.Size = new System.Drawing.Size(10, 10);
                lbl.TabIndex = 5;
                lbl.Text = "test";

                panel.Location = new System.Drawing.Point(1, 1);
                panel.Name = "panelSys";
                panel.Size = new System.Drawing.Size(20, 20);
                panel.TabIndex = 5;
                panel.Controls.Add(lbl);
                c.Controls.Add(panelSys);
            }

Hope you can help me thanks

2条回答
戒情不戒烟
2楼-- · 2019-08-28 21:35

Drawing to controls Should be done by adding a 'Paint' event to the control and then draw inside this event. You will get a 'Graphics' object through the EventArgs. Then you can force a draw of the control using the 'Invalidate' method of the control. Also Windows will call the Paint event on ita own sometimes.

Alternatively you can also create a normale using 'Bitmap.Create'. Draw to that and then assign it to a Picture control.

查看更多
The star\"
3楼-- · 2019-08-28 21:52

I am not sure why do you need InitOtuput function but if you want to draw from it you could do it like this:

private void InitOutput(object output)
{
    if (output is Control)
    {
        Control c = (Control)output;
        c.Paint += new System.Windows.Forms.PaintEventHandler(c_Paint);
        // Invalidate needed to rise paint event
        c.Invalidate();
    }
}
private void c_Paint(object sender, PaintEventArgs e)
{
    SolidBrush hb =  new SolidBrush(Color.Red);
    e.Graphics.FillRectangle(hb, 7, 10, 30 - 19, 5);
    e.Graphics.DrawString("test", DefaultFont, hb, new PointF(50, 50));
}

Additionaly you don't need to use label to draw text u can draw it using Graphics.DrawSting

查看更多
登录 后发表回答