2012-04-23 61 views
1

我的C#Windows-Forms項目出現問題。我正在畫一個正方形,我想在一個圖畫框裏面顯示這個正方形。我怎樣才能做到這一點?如何畫一個正方形到一個PictureBox?

這是我的函數用於繪製方形:

public void DrawingSquares(int x, int y)//the function gets x and y to know where to print the square. 
    { 
     Graphics graphicsObj; 
     graphicsObj = this.CreateGraphics(); 
     Pen myPen = new Pen(Color.Black, 5); 
     Rectangle myRectangle = new Rectangle(x, y, 100, 100); 
     graphicsObj.DrawRectangle(myPen, myRectangle); 
    } 

回答

2

my vs solution

using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Drawing.Imaging; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
    public Form1() 
    { 
     InitializeComponent(); 

     this.pictureBox1.Image = this.Draw(this.pictureBox1.Width, this.pictureBox1.Height); 
    } 

    public Bitmap Draw(int width, int height) 
    { 
     var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); 
     var graphics = Graphics.FromImage(bitmap); 
     graphics.SmoothingMode = SmoothingMode.AntiAlias; 
     graphics.FillRectangle(new SolidBrush(Color.Tomato), 10, 10, 100, 100); 

     return bitmap; 
    } 
    } 
} 

這是我Form1.cs的

你應該有一些呈三角

+0

當我的功能取代你的功能時,它的細節給了我很多對不起:對不起: – 2012-04-23 08:52:51

+0

錯誤名稱'PixelFormat'在當前上下文中不存在\t c:\ users \ 08_11_2010 \ documents \ visual studio 2010 \ Projects \ WindowsFormsApplication3 \ WindowsFormsApplication3 \ Form1.cs WindowsFormsApplication3 – 2012-04-23 09:00:53

+0

錯誤 'SmoothingMode' 並不在當前情況下\t存在C的名字:\用戶\ 08_11_2010 \文檔\ Visual Studio 2010的\項目\ WindowsFormsApplication3 \ WindowsFormsApplication3 \ Form1.cs中 WindowsFormsApplication3 – 2012-04-23 09:02:02

-1
public Bitmap Draw() 
{ 
    var bitmap = new Bitmap(width,height, PixelFormat.Format32bppArgb); 
    var graphics = Graphics.FromImage(bitmap); 
    graphics.SmoothingMode = SmoothingMode.AntiAlias; 
    graphics.FillRectangle(new SolidBrush(Color.Tomato), 10, 10, 100, 100); 
} 

this.pictureBox1.Image = new PieChart().Draw(); 

所以如果你只返回一個位圖,它的工作原理

+0

其中i showld鍋是什麼? – 2012-04-23 08:36:51

+0

在我的繪圖方塊功能 – 2012-04-23 08:37:13

+0

public Bitmap Draw取代你的方塊函數,你可以重新命名我寫的,如果你願意的話。 this.pictureBox1.Image = new PieChart()。Draw();屬於你想要的部分是否將你的圖片分配給圖像盒 – Pascal 2012-04-23 08:40:00

1

您必須添加一個PaintEventHandler您的圖片框中,並繪製矩形裏面它:

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    ... 
    e.Graphics.DrawRectangle(myPen, myRectangle); 
}