BLOG.CSHARPHELPER.COM: Draw smooth shapes on a bitmap so you don't need to redraw them in C#
Draw smooth shapes on a bitmap so you don't need to redraw them in C#
The example Draw smooth shapes in a form's Paint event handler in C# shows how to draw a picture in a form's Paint event handler. This is simple but the Paint event is raised every time the form grows larger or is covered and then exposed. If the drawing takes a long time, then the event handler can take a little while and the user may notice.
This example shows how to draw on a Bitmap once when the form loads. It sets a PictureBox control's Image property to the Bitmap and the PictureBox automatically redisplays it whenever necessary with no redrawing.
The following code shows how the example draws its picture.
// Make and display a Bitmap. private void Form1_Load(object sender, EventArgs e) { // Prepare the PictureBox. picDrawing.SizeMode = PictureBoxSizeMode.AutoSize; picDrawing.Location = new Point(0, 0);
// Make the Bitmap. Bitmap bm = new Bitmap(280, 110);
// Draw on it. using (Graphics gr = Graphics.FromImage(bm)) { // Draw smoothly. gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// Make a Rectangle to define the ellipse. Rectangle rect = new Rectangle(10, 10, 260, 90);
// Fill the ellipse. gr.FillEllipse(Brushes.LightGreen, rect);
// Outline the ellipse. using (Pen thick_pen = new Pen(Color.Blue, 5)) { gr.DrawEllipse(thick_pen, rect); } }
// Display the Bitmap. picDrawing.Image = bm; }
First the code prepares its PictureBox by setting SizeMode = AutoSize and moving the PictureBox into the form's upper left corner. (You could do this at design time but I wanted to the code emphasize the fact that SizeMode = AutoSize. That guarantees that the Bitmap is completely visible.)
Next the program makes a Bitmap and a Graphics object to draw on it.
The code sets the Graphics object's SmoothingMode property to get smooth drawing. It creates a Rectangle to define the ellipse, fills the ellipse, and then outlines it with a thick pen.
After all of the drawing, the code sets the PictureBox's Image property to the Bitmap.
Comments