C# PictureBox Drawing: Efficient Tips for Using Independent Methods
In a C# Forms application, you can draw custom graphics on the PictureBox control. However, users may encounter problems when trying to do this through a separate method.
question:
The user may want to create a method to conveniently draw circles on the PictureBox, but finds that the method does not produce the expected results. The problem method initializes the bitmap, graphic objects, and the brushes used to draw circles. However, when called in the Paint event handler of PictureBox, it cannot draw the circle correctly.
Solution:
To effectively use a separate method to draw on PictureBox, be sure to know whether the goal is to draw in the image displayed by PictureBox or directly on the control itself.
Method 1: Draw directly on the control
]To draw directly on the control (without affecting the image), use the Paint event handler of PictureBox, as shown below:
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawEllipse(Pens.Red, new Rectangle(3, 4, 44, 44));
}
In this case, the drawing is persistent, the graphics are bound to the control, following any resizing or moving of the control.
Method 2: Draw in the image
]To draw in an image displayed by PictureBox, create a separate method and draw using the Graphics object obtained from the Image property of PictureBox.
void drawIntoImage()
{
using (Graphics G = Graphics.FromImage(pictureBox1.Image))
{
G.DrawEllipse(Pens.Orange, new Rectangle(13, 14, 44, 44));
}
pictureBox1.Refresh();
}
After the drawing is completed, call the Refresh() method of PictureBox to update the display. In this case, the graphics are persistent to the image and are affected by any scaling or transformation of the image.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3