2011-05-26 40 views
0

我剛剛開始學習GDI +繪製線條,圓圈等系統。我創建了一個組件(掃描儀),它繼承了一個Panel來繪製(不確定面板或圖片框是最好)。Fix Graphics繪圖區域大小

在「掃描儀」我正在其上畫一個圓圈。該組件可以添加到winform中,並且在winform調整大小時使用對接將調整大小。此刻,我得到組件的大小來計算圓的大小,但我想要做的事情基本上是說,無論組件大小是多少,「畫布」總是300 x 300寬,所以我可以說該圓應位於25,25,大小爲250x250。

正如您可能從名稱「掃描儀」中猜出的那樣,我想在它上面繪製點,但這些將從中心(150,150)位置計算得出。

下面是我有的代碼,基本上繪製了圓圈。

非常感謝您的幫助。

public partial class Scanner : Panel 
{ 
    public Scanner() { 
     InitializeComponent(); 
     this.DoubleBuffered = true; 
    } 

    protected override void OnPaint(PaintEventArgs e) { 
     Graphics g = e.Graphics; 
     Draw(g); 
     base.OnPaint(e); 
    } 
    protected override void OnResize(EventArgs e) { 
     Graphics g = this.CreateGraphics(); 
     Draw(g); 
     base.OnResize(e); 
    } 

    private void Draw(Graphics g) { 
     g.Clear(Color.Black); 
     g.PageUnit = GraphicsUnit.Pixel; 
     Pen green = new Pen(Color.Green); 
     Font fnt = new Font("Arial", 10); 
     SolidBrush sb = new SolidBrush(Color.Red); 

     int pos = (this.Width < this.Height ? this.Width : this.Height)/2; 
     int size = (int)(pos * 1.9); 
     pos -= ((int)size/2); 
     g.DrawEllipse(green, pos, pos, size, size); 
     g.DrawString(this.Width.ToString(), fnt, sb, new Point(0, 0)); 
    } 
} 
+0

我可能失去了一些東西,但是... g.DrawEllipse(綠色,25,25,250,250);做你想要的...? – 2011-05-26 13:42:01

+0

我想在300x300圖像上繪製「掃描儀」,然後將該圖像轉移到窗體上的實際控件上,實際控件的大小可以是任意大小(但始終爲正方形),所以如果控件是500x500,那麼300x300圖像將被放大到500x500。希望這可以幫助 – harag 2011-05-26 14:13:47

回答

1

根據您最近的評論,我理解你想要做您的繪圖一個固定大小的畫布上,並繪製控制這裏面的帆布,大如將適合的控制。

嘗試下面的代碼:

public class Scanner : Panel 
{ 
    private Image _scanner; 

    public Scanner() 
    { 
     this.SetStyle(ControlStyles.ResizeRedraw, true); 

     CreateScanner(); 
    } 

    private void CreateScanner() 
    { 
     Bitmap scanner = new Bitmap(300, 300); 
     Graphics g = Graphics.FromImage(scanner); 

     g.DrawEllipse(Pens.Green, 25, 25, 250, 250); 

     g.Dispose(); 
     _scanner = scanner; 
    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 

     int shortestSide = Math.Min(this.Width, this.Height); 

     if (null != _scanner) 
      e.Graphics.DrawImage(_scanner, 0, 0, shortestSide, shortestSide); 
    } 

} 
+0

並回答您的其他問題,除非您想使用其現有功能,否則實際上並不需要從Panel或Picturebox派生。你可以從Control中派生出來。 – 2011-05-26 14:41:09

+0

非常感謝,似乎很好! – harag 2011-05-26 18:51:08