1

我的 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);
    }
4

3 回答 3

2

我的 vs 解决方案

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

你应该有类似的东西

于 2012-04-23T08:44:25.020 回答
1

You must add a PaintEventHandler inside your picture box and draw the rectangle inside it:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    ...
    e.Graphics.DrawRectangle(myPen, myRectangle);
}
于 2012-04-23T08:41:49.890 回答
-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();

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

于 2012-04-23T08:35:04.930 回答