I want to use a PictureBox as a canvas and draw some text on it and save.
I wrote this piece of code but I'm not sure if im doing this the correct way:
Bitmap b = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height)); // i used this code to make the background color white
g.DrawString("some text", new Font("Times New Roman", 20), new SolidBrush(Color.Red), new PointF(10, 10));
pictureBox1.Image = b;
This code works well but when I want to change the background color of the image I have to redraw the text.
Is there a way to change the background color without having to redraw the text?
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:
You seem to think that repeating anything, like redrawing the text is wrong. It is not. Windows redraws huge numbers of things all the time..
You have mixed two of the tasks which really should be separate.
You have not parametrizied anything, most notably the drawing of the text should use several variables:
Font
Brush
Position
the text itself
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);
}
}
Related
I need to create some simple graphics in a windows form using C#. By simple I mean lines, circles etc. However, when I draw e.g. a filled circle, the edge is not smooth (as expected when drawing a circle using square pixels), but when drawing the same circle with the same number of pixels in a vector program it looks perfect. I have been drawing in Inkscape for this example.
Maybe the vector software uses some sort of render function to smooth the colors, but is this possible in C# without creating too much code? Here is an example of the code, which is using Graphics to create a canvas to draw on.
private void StatGraphicsPanel_Paint(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics;
Brush brush = Brushes.Aqua;
canvas.FillEllipse(brush, 0, 0, 10, 10);
}
Solution
This code does the trick:
private void StatGraphicsPanel_Paint(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics;
canvas.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Brush brush = Brushes.Aqua;
canvas.FillEllipse(brush, 0, 0, 10, 10);
}
You want to use the System.Drawing.Graphics.SmoothingMode property. Before beginning to use your Graphics object, do this:
canvas.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
That should give you a nice anti-aliased ellipse instead of the default jaggy one.
Similarly, if you want to draw high-quality text in an image, use the System.Drawing.Graphics.TextRenderingHint property.
As others have mentioned in comments, you might want to consider using WPF instead. WinForms are dated.
Hey everyone, a new guy here in C#.Net.
I'm trying to make an application like Ms Paint, of course much simpler, and I'm stuck.
The problem is this.
In pictureBox, I'm drawing grid lines on the PictureBox, after that I'm reading a .map(A Mapper3 file) and want to draw onto grid lines, but When I draw the map, The grid lines disappers.
I think the problem is because of the PictureBox Image becomes null while I'm drawing the map. How can I overcome this, is there any tricks?
Thanks for the replies from now on, and sorry for my bad English...
My best Regards...
Do you using winforms? If yes, you actually dont need picture box for working area. I think more appropriate would be Graphics class on form or panel. You have lost lines because of form repaint circle, put your drawing code into form paint handler and picture would be repainted when it needed. In some cases you can need to manual trigger repaint circle, for this purposes you should use Invalidate method of your form.
For example, add this code to paint handler:
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Drawing vertical lines
for (int x = 5; x < this.ClientRectangle.Width; x+=5)
{
e.Graphics.DrawLine(Pens.Gray, new Point(x, 0), new Point(x, this.ClientRectangle.Height));
}
// Drawing horisontal lines
for (int y = 5; y < this.ClientRectangle.Width; y += 5)
{
e.Graphics.DrawLine(Pens.Gray, new Point(0, y), new Point(this.ClientRectangle.Width,y));
}
}
You also may use Graphics in button click handler this way:
Graphics g = Graphics.FromHwnd(this.Handle);
g.FillEllipse(Brushes.Beige, new Rectangle(10, 10, 10, 10));
But in this case all you have drawn would be erased during form's repaint circle and you will have to repeint it in form paint handler
[EDIT]
Ok, for example you have pictureBox1 on your form, you can easly draw into it with help of Bitmap class in this way:
// Draw into bitmap
Bitmap bmp = new Bitmap(150, 150);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.Green, new Rectangle(25, 75, 10, 30));
// Set bitmap into picture box
pictureBox1.Image = bmp;
In this case you have no need to redraw your paintings, picture box would do it for you. Dont forget to set BackColor ot picture box to Transparent if you prefer to show paintings from below of picture box.
You have to draw everything including the grid lines whenever the paint event raised, if you are concerned about performance you may detect the clipping area and only draw that portion.
Good luck.
I have drawn a circle in windows form
Pen pen = new Pen(Color.Black, 3);
Graphics gr = this.CreateGraphics();
gr.DrawEllipse(pen, 5,5,20,20);
How to delete it...
You have to clear your Graphic:
Graphics.Clear();
But all drawn figures will be cleared. Simply, you will then need to redraw all figures except that circle.
Also, you can use the Invalidate method:
Control.Invalidate()
It indicates a region to be redrawn inside your Graphics. But if you have intersecting figures you will have to redraw the figures you want visible inside the region except the circle.
This can become messy, you may want to check out how to design a control graph or use any graph layout library.
You can invalidate the draw region you want to refresh for example:
this.Invalidate();
on the form...
Assuming you're subscribing to the Paint event or overriding the protected OnPaint routine, then you will need to perform something like this:
bool paint = false;
protected override void OnPaint(object sender, PaintEventArgs e)
{
if (paint)
{
// Draw circle.
}
}
Then when you want to stop painting a circle:
paint = false;
this.Invalidate(); // Forces a redraw
You can make a figure of same dimensions using the backColor of your control in which you are drawing
use after your code to clear your figure.
Pen p = new Pen(this.BackColor);
gr.DrawEllipse(p, 5,5,20,20);
In fact, you can delete your circle and nothing but your circle.
Everything you need is something like a screenshot of the "before state" of the area you want to clear, to make a TextureBrush from it. You can achieve that step by something like this:
Bitmap _Background = new Bitmap(this.Width, this.Height);
Graphics.FromImage(_Background).CopyFromScreen(this.Left, this.Top, 0, 0, this.Size);
The first line will give you a bitmap in your windows forms size. The second line will save a screenshot of it in the _Background-bitmap.
Now you create a TextureBrush out of it:
Brush brsBackground = new TextureBrush(_Background);
The next thing you need are the dimensions of your circle, so you should save them into a variable, if they are not a fix value. When you got them at hand, you can clear the specific area like this:
Graphics gr = this.CreateGraphics();
gr.FillEllipse(brsBackground, 5, 5, 20, 20); // values referred to your example
Done!
Even complex figures are able to be deleted by this, like a GraphicsPath for example:
GraphicsPath gp = new GraphicsPath(); // any kind of GraphicsPath
gr.FillRegion(brsBackground, new Region(gp));
You don't "delete" it per se, there's nothing to delete. It's a drawing, you draw something else over it or you can call the Graphics.Clear() method.
If u are using Invalidate() and is not working, make a panel.Refresh().
That will work on you.
just make another control with the attributes etc. that you want, make the visibility to false and set the region of the control to the other control like this:
pen.Region = pen2.Region;
It is very simple to delete a drawn circle from c.
There is only four steps:-
Open turbo app
go to the command where you had drawn the circle
drag the command
click on delete button
I'm working on a Map Editor for an XNA game I'm designing in my free time. The pieces of art used in the map are stored on a single texture and rectangles are stored with coordinates and widths etc.
In the winforms application I can add segments by selecting the segment I want from a listbox, which is populated from the array of possible segments.
Problem is I would like to be able to show a preview of the segment selected and, since it is stored on a common texture, I cant simply set a picturebox to display the image.
Is there anyway of using the rectangle information (.x, .y, .width, .height) to display only the section of the image in a picturebox, or to blit the section to a bitmap and display that?
Many Thanks
Michael Allen
You probably want to look into the GDI library. Using the Image or Bitmap object and the Graphics.DrawImage() together will get what you're looking for.
private void DrawImageRectRect(PaintEventArgs e)
{
// Create image.
Image newImage = Image.FromFile("SampImag.jpg");
// Create rectangle for displaying image.
Rectangle destRect = new Rectangle(100, 100, 450, 150);
// Create rectangle for source image.
Rectangle srcRect = new Rectangle(50, 50, 150, 150);
GraphicsUnit units = GraphicsUnit.Pixel;
// Draw image to screen.
e.Graphics.DrawImage(newImage, destRect, srcRect, units);
}
You also might be interested in using XNA within your WinForm instead of using PictureBoxes and GDI. It's not 100% supported yet, but a tutorial on that can be found here.
You can use Graphics.DrawImage() and that will accept a Rectangle.
I'd like to draw antialiased text on a transparent bitmap and have the antialiasing drawn as alpha blended pixels. This way, I can draw the bitmap onto any color surface (or an image, for that matter) and the antialiasing still looks fine.
Here is a simplified sample showing the problem:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Bitmap bitmap = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.Empty);
g.DrawString("hello world", new Font(this.Font.FontFamily, 24), Brushes.Blue, new Point(50, 50));
e.Graphics.DrawImage(bitmap, new Point(0, 0));
}
And here is the result:
The ultimate goal of this is to use UpdateLayeredWindow to draw my transparent alpha blended window. I am creating a Conky-like application, and I'd like to be able to use ClearType rendering for text (this is easy without antialiasing, of course).
Currently, I grab the screen behind the form, draw that, and then draw my text. It looks good, but has to be updated and is slow to draw. Any other ideas to accomplish drawing text on the desktop would also be welcome.
Your text is displayed as it is because you have ClearType subpixel anti-aliasing mode enabled (which is the default on Vista and above). ClearType, by definintion, cannot play nice with alpha channel, since it blends colors, and thus isn't background-agnostic. So it ignores the alpha channel, and blends to black (which is your transparent color otherwise is). You need to enable plain grayscale anti-aliasing for the desired effect:
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
I'm not sure if it's really necessary, but if you want to do alpha-blending, you should specify a 32-bit image:
Bitmap bitmap = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Using your example, I was able to make the text look decent by adding a text rendering hint:
g.Clear(Color.Empty);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.DrawString("hello world", new Font(this.Font.FontFamily, 24), Brushes.Blue, new Point(50, 50));
Is this doing what you want, or just hiding the problem?