Click here to Skip to main content
15,741,981 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to draw a rectangle 9x9 on my pictureBox and then save it. How can I do it?
Updated 13-Dec-14 4:22am

1 solution

The first step would be to create the Graphics object to work for the drawing. You cannot draw directly, you are required to create a Bitmap, and use the Graphics object to create different things on it.

You can create your own Bitmap, by passing your pictureBox (Image) to it, and make the Graphics by it. Like this,

// suppose bitmap is the object
Graphics gr = Graphics.FromImage(bitmap);

.. now gr would be the actual graphics, that would represent the bitmap of your image and you can now work on it. You can draw different shapes on it.

To draw a simple Rectangle you are required to call DrawRectangle() function.

// pen is used as the color for the borders
// rect is the bounds for the rectangle, pass the 9x9 area to it
gr.DrawRectangle(pen, rect);

.. now it will have the rectangle on it, add this (updated) instance of the Bitmap to the PictureBox to show it on the screen or just save it.

As Bill has mentioned in the comments, I would like to add that piece of information to my answer. It is a good approach to add shapes to the graphics object for the image in the Paint Event[^]. Paint event is raised when you're going to add shapes to the control for rendering; trust me there is no painter involved. You can simply just attach an event handler to the control like you do for the Click event.

Example code for the Paint Event handler is in the link I attached.

Entire directory for all of the methods of the Graphics object can be found here[^].
Share this answer
Avenger1 13-Dec-14 10:40am    
its good for save it
and now how can i make rectangles like puzzle on my image?
With Respect
Afzaal Ahmad Zeeshan 13-Dec-14 10:47am    
By using different algorithms and designs. Make them up, and style them and add them in the Graphics. But this would be a second question.

If this answer above helped you out, Mark it as answer.

BillWoodruff 13-Dec-14 23:52pm    
May I suggest you add to this (good) answer the information that you need to do the drawing in the Paint Event in order for the raster you create to persist ?
Afzaal Ahmad Zeeshan 14-Dec-14 3:29am    
I have added this and attached the link for the Paint Event! :-)

Thanks Bill,
BillWoodruff 14-Dec-14 4:08am    
+5 :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900