如何在PictureBox中绘制一个正方形?

时间:2012-04-23 08:31:49

标签: c# winforms picturebox

我的C#Windows-Forms项目有问题。我想画一个正方形,我想在一个图片框中显示正方形。我怎么能这样做?

这是我绘制正方形的函数:

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);
    }

3 个答案:

答案 0 :(得分: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

你应该有类似的东西

答案 1 :(得分:1)

您必须在图片框中添加PaintEventHandler并在其中绘制矩形:

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

答案 2 :(得分:-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();

所以,如果你只是返回一个位图,那就可以了