Reputation: 75
I have a problem with my C# Windows-Forms project. I am trying to draw a square and I want to display the square inside a picture-box. How can I do that?
This is my function for drawing the square:
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);
}
Upvotes: 1
Views: 11684
Reputation: 2214
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;
}
}
}
this is my Form1.cs
you should have something simillar
Upvotes: 2
Reputation: 22011
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);
}
Upvotes: 1
Reputation: 2214
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();
so if you just return a bitmap, it works
Upvotes: -1