Writing a Paint program is a lot of fun, but you need to plan ahead for all or most of the features you want.
So far you have these:
- A background you can change
- A way to modify an image by drawing text on it
- The need to save it all to a file
Here are a few more things you will need:
- Other tools than just text, like lines, rectangles etc..
- A choice of colors and pens with widths
- A way to undo one or more steps
Here are few thing that are nice to have:
- A way to help with drawing and positioning with the mouse
- Other type backgrounds like a canvas or pergament paper
- The ability to draw with some level of tranparency
- A redo feature (*)
- Rotation and scaling (***)
- Levels (*****)
Some things are harder (*
) or a lot harder (***
) than others, but all get hard when you decide to patch them on too late..
Do read this post (starting at 'actually') about PictureBoxes
, which explain how it is the ideal choice for a Paint program.
Your original piece of code and your question have these problems:
The same will be true once you draw lines or rectangles..
So here are the hints how do get it right:
Use the BackgroundColor
and/or the BackgroundImage
of the Picturebox
to dynamically change the background!
Collect all things to draw in a List<someDrawActionclass>
Combine all drawings by drawing it into he Picturebox's Image
Use the Paint
event to draw supporting things like the temporary rectangle or line while moving the mouse. On MouseUp
you add it to the list..
So, coming to the end, let's fix your code..:
You set the backgound with a function like this:
void setBackground(Color col, string paperFile)
{
if (paperFile == "") pictureBox1.BackColor = col;
else pictureBox1.BackgroundImage = Image.FromFile(paperFile);
}
you can call it like this: setBackground(Color.White, "");
To draw a piece of text into the Image
of the PictureBox
, first make sure you have one:
void newCanvas()
{
Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
pictureBox1.Image = bmp;
}
Now you can write a function to write text. You really should not hard-code any of the settings, let alone the text! This is just a quick and very dirty example..:
void drawText()
{
using (Font font = new Font("Arial", 24f))
using (Graphics G = Graphics.FromImage(pictureBox1.Image))
{
// no anti-aliasing, please
G.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
G.DrawString("Hello World", font, Brushes.Orange, 123f, 234f);
}
pictureBox1.Invalidate();
}
See here and here for a few remarks on how to create a drawAction class to store all the things your drawing is made up from..!
The last point is how to save all layers of the PictureBox
:
void saveImage(string filename)
{
using (Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height))
{
pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
bmp.Save("yourFileName.png", ImageFormat.Png);
}
}