簡體   English   中英

在面板上繪制矩形

[英]Drawing a rectangle over panel

我需要在面板上繪制一個矩形。 我事先不知道顏色,我在運行時得到顏色,我不知道如何不將顏色設置為固定值,其次-當我嘗試繪制矩形時,它什么也沒做。 這是我的代碼,應該繪制矩形(實際上它在另一個項目中也是如此,但是那只是簡單的形式,而不是面板)

    Graphics g;  
    g = CreateGraphics();  
    Pen p;  
    Rectangle r;  
    p = new Pen(Brushes.Blue); 
    r = new Rectangle(1, 1, 578, 38);  
    g.DrawRectangle(p, r);`  

因此,我需要用變量替換(Brushes.Blue),並且需要在此代碼中設置的坐標上的面板上繪制矩形。

構建你的Pen使用Pen(Color)構造函數,而不是Pen(Brush)之一。 然后,一旦知道就可以定義顏色。

您應該在面板的Paint事件中執行繪圖。 只要Windows決定是時候重新繪制面板,並且PaintEventArgs包含可以在其上繪制矩形的Graphics對象,就會發生此事件。

Brush是一個抽象類,但是您可以在運行時使用SolidBrush對象創建自定義的彩色畫筆:

int red = 255;
int green = 0;
int blue = 0;
Brush myBrush = new SolidBrush(Color.FromArgb(red, green, blue));

這個給你:

private Color _color;                 // save the color somewhere
private bool iKnowDaColor = false;    // this will be set to true when we know the color
public Form1() {
    InitializeComponents();

    // on invalidate we want to be able to draw the rectangle
    panel1.Paint += new PaintEventHandler(panel_Paint);
}

void panel_Paint(object sender, PaintEventArgs e) {
    // if we know the color paint the rectangle
    if(iKnowDaColor) {
        e.Graphics.DrawRectangle(new Pen(_color),
            1, 1, 578, 38);
    }
}

當您知道顏色時:

_color = ...
iKnowDaColor = true;

// causes the panel to invalidate and our painting procedure to be called
panel.Invalidate();

我沒有測試過,但是應該給你基本的想法。

我認為更好的方法是擴展Panel類並添加一些自定義OnPaint事件邏輯。

public class PanelRect : Panel
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        using (Graphics g = e.Graphics)
        {
            Rectangle rect = ClientRectangle;
            rect.Location = new Point(20, 20);                  // specify rectangle relative position here (relative to parent container)
            rect.Size = new Size(30, 30);                       // specify rectangle size here

            using (Brush brush = new SolidBrush(Color.Aqua))    // specify color here and brush type here
            {
                g.FillRectangle(brush, rect);
            }
        }
    }
}

PS這不是高級示例,但可能會對您有所幫助。 您可以將大小,位置和顏色等移至屬性,以便可以從設計人員輕松更改它們。

PSPS如果需要一個非填充矩形,只需使用Pen對象而不是Brush(您也可以將FillRectangle更改為更合適的對象)。

將以下代碼放在適當的位置:

Graphics g = panel1.CreateGraphics();
int redInt=255, blueInt=255, greenInt=255; //255 is example, give it what u know
Pen p = new Pen(Color.FromArgb(redInt,blueInt,greenInt));
Rectangle r = new Rectangle(1, 1, 578, 38);
g.DrawRectangle(p, r);

如果您想在其他地方繪制矩形(例如表格),則可以執行g = this.CreateGraphics

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM