Drawing on the bottom of a BufferedGraphics - c#

I have a BufferedGraphics instance and I draw some graphs on it. I'd like to create a function called DrawLegends that takes an instance of BufferedGraphics and draws two strings as legend.
I can create a PointF instance that points to (0, 0), but I want to put the legend on the bottom. How should I proceed with that? Can I do it with the BufferedGraphics instance or would I also need the panel that I'm drawing on?

The important thing is that you need to know the dimensions (mainly height) of the drawing canvas (i.e. the panel). This will be used to ultimately calculate the position of the legend. So if you don't have the height information stored elsewhere then yes, you will have to use the panel to some degree

At the end of the day pretty much all objects which are drawn to the screen can be manually drawn on, as under the covers they have or expose a graphics object to paint onto when you feel like it.
So if you do your drawing on a graphics object or whatever you are currently using, then when you are done drawing just paint that graphics object onto whatever control you want to display it in. As you can treat graphics objects a bit like images. There is no reason why you cannot pass in the underlying controls graphics object you want to paint onto rather than making your own graphics object, but if you have a method which does:
void DrawGraph(string xLegend, string yLegend, IList<XYValues> values, Graphics graphics);
Then you can draw onto that graphics object with the data, call invalidate and your done.

Related

C# : Remove Paint Event from PictureBox

Sorry for my bad English.
I have a picturebox where I draw 100000 shapes (but there may be more).
The drawing is made in the Paint Handler of the picturebox.
The problem is : When I Resize the form (where the picturebox is), use the scrollbar of the panel which contain it, come from another application, ... the paint handler is called...
But the paint process takes quite some time and the user must wait until the paint have finished...
I tried the folowing :
Create a bitmap where i draw the shapes
In the paint handler, i copy the bitmap in the picturebox
NB : The size and the content of the picturebox can change, so the bitmap must also change.
The creation of the bitmap + restoration of the bitmap make the application slower than before :
Bitmap bmp = new Bitmap(picturebox.Width, picturebox.Height);
// draw in Graphics.FromImage(bmp);
picturebox.Invalidate();
bmp.Dispose();
I also tried with a boolean flag : canRedraw.
I set it true when the content of the picturebox change and then I call picturebox.Invalidate(). In the paint handler, I check if (canRedraw) and if so, I redraw the content (and canRedraw = false), else I make nothing.
But with this last solution, when I make something with the form, my picturebox is cleared...
Do you have any idea of how I can make this :
If you are a method that change the content of the picturebox then you can redraw the picturebox, else you leave the visual content of the picturebox unchanged.
Can you help me ?
Thank you very much :)
If you're not using any other functionality of the PictureBox, try replacing it with a UserControl of your own. Then take the following steps in your UserControl:
Set DoubleBuffered property of the control to True.
Always check e.ClipRectangle property to get the area that needs to be redrawn. Then loop through the collection of your shapes and for each shape, try to figure our whether it intersects with the ClipRectangle. I don't know what kind of shapes you have, but there are fairly fast implementations available for most shapes, including polygon, that can check whether two polygons intersect or not. A good article about polygons intersection is available in this article, including c# code. (Note that if your shapes are rectangles, circles or triangles, the intersection problem becomes much easier and faster to compute)
Paint a shape only if it intersects with ClipRectangle.
Besides streamlining the Paint as dotNet suggest the other way to do it is pretty much what you tried, but you need to do it right:
Yes, do draw into a Bitmap but not in the Paint event, which will be called unnecessarily and then still take too much time! Instead draw only when you know that your data have changed and need to be redrawn!
You didn't tell us just what you draw but the drawing should be done like this:
void drawStuff()
{
Bitmap bmp = new Bitmap(pictureBox.ClientSize.Width, pictureBox.ClientSize.Height);
using (Graphics G = Graphics.FromImage(bmp) )
{
// do all your drawing stuff here!!
}
pictureBox.Image = bmp;
}
Call this function whenever you want the data to be drawn again!
Now you can leave the Paint event empty, as the Image if buffered by the System and you can still use the PictureBox.Zoom or Image.Save..

Photoshop like background on transparent image

I'm making a graphics editor for my class project and i want to make so that when, for example a user loads a picture in to the editor or or draw something in the PictureBox, all the alpha parts are shown the chessboard like background.
My idea is that when I create a PictureBox with transparent background set, I create another one behind it, set its BackColor to white and add grey images 50x50, alternately horizontally and vertically. Is that a good approach to the problem? If, not do You have any suggestions?
In Photoshop, for example, I create image 1600x1600. When I zoom to a certain level, it shrinks the boxes and adds more of them to fill the image. If You'we used Photoshop of similar program you know what I mean. Now, how would I go about achieving the same effect?
Creating a Photoshop-like program is a fun project.
There will be many challenges along your way and it is well worth thinking ahead a little..
Here is a short and incomplete list of things to keep in mind:
Draw- and paint actions
Undo, redo, edit
Multiple layers
Zooming and scrolling
Saving and printing
So getting a checkerboard background is only the start of a long journey..
Using a PictureBox as the base canvas is a very good choice, as its several layers will help. Here is a piece of code that will provide you with a flexible checkerboard background, that will keep its size even when you scale the real graphics:
void setBackGround(PictureBox pb, int size, Color col)
{
if (size == 0 && pb.BackgroundImage != null)
{
pb.BackgroundImage.Dispose();
pb.BackgroundImage = null;
return;
}
Bitmap bmp = new Bitmap(size * 2, size * 2);
using (SolidBrush brush = new SolidBrush(col))
using (Graphics G = Graphics.FromImage(bmp) )
{
G.FillRectangle(brush, 0,0,size, size);
G.FillRectangle(brush, size,size, size, size);
}
pb.BackgroundImage = bmp;
pb.BackgroundImageLayout = ImageLayout.Tile;
}
Load an Image for testing and this is what you'll get, left normal, right zoomed in:
Yes, for saving this background should be removed; as you can see in the code, passing in a size = 0 will do that.
What next? Let me give you a few hints on how to approach the various tasks from above:
Scrolling: Picturebox can't scroll. Instead place it in a Panel with AutoScroll = true and make it as large as needed.
Zooming: Playing with its Size and the SizeMode will let you zoom in and out the Image without problems. The BackgroundImage will stay unscaled, just as it does in Photoshop. You will have to add some more code however to zoom in on the graphics you draw on top of the PB or on the layers. The key here is scaling the Graphics object using a Graphics.MultiplyTransform(Matrix).
Layers: Layers are imo the single most useful feature in PhotoShop (and other quality programs). They can be achieved by nesting transparent drawing canvases. Panels can be used, I prefer Labels. If each is sitting inside the one below it and the one at the bottom has the PB as its Parent, all their contents will be shown combined.
Don't use the Label directly but create a subclass to hold additional data and know-how!
Changing their order is not very hard, just keep the nested structure in mind and intact!
Hiding a layer is done by setting a flag and checking that flag in the painting actions
Other data can include a Name, Opacity, maybe an overlay color..
The layers should also be shown in a Layers Palette, best by creating a thumbnail and inserting a layer userobject in a FlowLayoutPanel
Draw Actions: These are always the key to any drawing in WinForms. When using the mouse to draw, each such activity creates an object of a DrawAction class you need to design, which holds all info needed to do the actual drawing, like:
Type (Rectangle, filledRectangle, Line, FreeHandLine (a series of Points), Text, etc.etc..)
Colors
Points
Widths
Text
The layer to draw on
maybe even a rotation
Along with the LayerCanvas class the DrawAction class will be the most important class in the project, so getting its design right is worth some work!
Only the topmost layer will receive the mouse events. So you need to keep track which layer is the active one and add the action to its actions list. Of course the active layer must also be indicated in the Layers Palette.
Since all drawing is stored in List(s), implementing a unlimited undo and redo is simple. To allow for effective drawing and undo, maybe a common action list and an individual list for each layer is the best design..
Undo and Redo are just matter of removing the last list element and pushing it onto a redo-stack.
Editing actions is also possible, including changing the parameters, moving them up or down the actions list or removing one from the middle of the list. It help to show an Actions Palette, like F9 in PhotoShop.
To flatten two or more layers together all you need is to combine their action lists.
To flatten all layers into the Image you only need to draw them not onto their canvas but into the Image. For the difference of drawing onto a control or into a Bitmap see here! Here we have the PictureBox.Image as the second level of a PB's structure above the Background.Image. (The 3rd is the Control surface, but with the multiple layers on top we don't really need it..)
Saving can be done by either by Image.Save() after flattening all Layers or after you have switched off the BackgroundImage by telling the PB to draw itself into a Bitmap ( control.DrawToBitmap() ) which you can then save.
Have fun!

Best practice for OnPaint, Invalidate, Clipping and Regions

I have a User Control with completely custom drawn graphics of many objects which draw themselves (called from OnPaint), with the background being a large bitmap. I have zoom and pan functionality built in, and all the coordinates for the objects which are drawn on the canvas are in bitmap coordinates.
Therefore if my user control is 1000 pixels wide, the bitmap is 1500 pixels wide, and I am zoomed at 200% zoom, then at any given time I would only be looking at 1/3 of the bitmap's width. And an object which has a rectangle starting at point 100,100 on the bitmap, would appear at point 200,200 on the screen provided you were scrolled to the far left.
Basically what I need to do is create an efficient way of redrawing only what needs to be redrawn. For example, if I move an object, I can add the old clip rectangle of that object to a region, and union the new clip rectangle of that object to that same region, then call Invalidate(region) to redraw those two areas.
However doing it this way means I have to constantly convert the objects bitmap coordinates into screen coordinates before supplying them to Invalidate. I have to always assume that the ClipRectangle in PaintEventArgs is in screen coordinates for when other windows invalidate mine.
Is there a way that I can make use of the Region.Transform and Region.Translate capabilities so that I do not need to convert from bitmap to screen coordinates? In a way that it won't interfere with receiving PaintEventArgs in screen coordinates? Should I be using multiple regions or is there a better way to do all this?
Sample code for what I'm doing now:
invalidateRegion.Union(BitmapToScreenRect(SelectedItem.ClipRectangle));
SelectedItem.UpdateEndPoint(endPoint);
invalidateRegion.Union(BitmapToScreenRect(SelectedItem.ClipRectangle));
this.Invalidate(invalidateRegion);
And in the OnPaint()...
protected override void OnPaint(PaintEventArgs e)
{
invalidateRegion.Union(e.ClipRectangle);
e.Graphics.SetClip(invalidateRegion, CombineMode.Union);
e.Graphics.Clear(SystemColors.AppWorkspace);
e.Graphics.TranslateTransform(AutoScrollPosition.X + CanvasBounds.X, AutoScrollPosition.Y + CanvasBounds.Y);
DrawCanvas(e.Graphics, _ratio);
e.Graphics.ResetTransform();
e.Graphics.ResetClip();
invalidateRegion.MakeEmpty();
}
Since a lot of people are viewing this question I will go ahead and answer it to the best of my current knowledge.
The Graphics class supplied with PaintEventArgs is always hard-clipped by the invalidation request. This is usually done by the operating system, but it can be done by your code.
You can't reset this clip or escape from these clip bounds, but you shouldn't need to. When painting, you generally shouldn't care about how it's being clipped unless you desperately need to maximize performance.
The graphics class uses a stack of containers to apply clipping and transformations. You can extend this stack yourself by using Graphics.BeginContainer and Graphics.EndContainer. Each time you begin a container, any changes you make to the Transform or the Clip are temporary and they are applied after any previous Transform or Clip which was configured before the BeginContainer. So essentially, when you get an OnPaint event it has already been clipped and you are in a new container so you can't see the clip (your Clip region or ClipRect will show as being infinite) and you can't break out of those clip bounds.
When the state of your visual objects change (for example, on mouse or keyboard events or reacting to data changes), it's normally fine to simply call Invalidate() which will repaint the entire control. Windows will call OnPaint during moments of low CPU usage. Each call to Invalidate() usually will not always correspond to an OnPaint event. Invalidate could be called multiple times before the next paint. So if 10 properties in your data model change all at once, you can safely call Invalidate 10 times on each property change and you'll likely only trigger a single OnPaint event.
I've noticed you should be careful with using Update() and Refresh(). These force a synchronous OnPaint immediately. They're useful for drawing during a single threaded operation (updating a progress bar perhaps), but using them at the wrong times could lead to excessive and unnecessary painting.
If you want to use clip rectangles to improve performance while repainting a scene, you need not keep track of an aggregated clip area yourself. Windows will do this for you. Just invalidate a rectangle or a region that requires invalidation and paint as normal. For example, if an object that you are painting is moved, each time you want to invalidate it's old bounds and it's new bounds, so that you repaint the background where it originally was in addition to painting it in its new location. You must also take into account pen stroke sizes, etc.
And as Hans Passant mentioned, always use 32bppPArgb as the bitmap format for high resolution images. Here's a code snippet on how to load an image as "high performance":
public static Bitmap GetHighPerformanceBitmap(Image original)
{
Bitmap bitmap;
bitmap = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppPArgb);
bitmap.SetResolution(original.HorizontalResolution, original.VerticalResolution);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(original, new Rectangle(new Point(0, 0), bitmap.Size), new Rectangle(new Point(0, 0), bitmap.Size), GraphicsUnit.Pixel);
}
return bitmap;
}

TextRenderer with Graphics transform

I've been working on a custom control and I've run into an issue with TextRenderer acting a bit surprisingly. In my OnPaint event I apply transform to the Graphics object to compensate for the scroll position like this:
e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
Then I pass the graphic object to all sub elements of the control so that they paint themselves onto it. One of this elements should draw text string onto the graphics surface. And this is where I've got an issue. This line seems to work correctly when scrolling:
e.Graphics.DrawString(this.Text, this.Font, brush, new PointF(this.Rectangle.X, this.Rectangle.Y));
But when I use TextRenderer I get a completely different result. Heres the text line that supposed to draw the text:
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.Rectangle, this.TextColor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform);
I thought that these two lines should produce the same result. But for some reason the second one applies the graphics transform differently and as a result, when I scroll the control all the text lines move around with different speed than the rest of the elements on the drawing surface. Could someone explain me why this is happening?
Here's my best guess at this: TextRenderer.DrawText is GDI-based and therefore resolution-dependant. Graphics.DrawString is GDI+ and therefore resolution-independant. See also this article.
Since you say that the texts "move around with different speed", probably what happens is that the GDI call uses a different "default" resolution than the one your Graphics object has. That'd mean that you'd have to adjust your AutoScrollCoordinates to respect the difference between your Graphics object resolution and the "default" GDI resolution.

In .NET, How can I draw shapes on a picture?

I'm doing a software where I need to put squary bordering fields on a satelite map (.png image), so that the fields can be clicked.
What is the best way to add shapes on a picture and associate them with data ?
Overlay a custom-draw UserControl on top of the Image control. Make part of it transparent to reveal the underlying image, but still be able to capture the mouse interaction.
You will have to calculate the exact position (pixel offset from the map top-left corner) of your control to overlay the proper map area. How you calculate that offset and the actual size of your custom control depends on the map zoom level and whether you use GPS coordinates or image recognition to determine which area needs to be overlayed.
Graphics.FillPolygon()
Is your friend. Hit testing is relatively trivial, with several algorithms available
You want to use the System.Drawing namespace to initially create a graphics object from your source image..then you want to draw on top of it, and finally export your edited graphics object to the filesystem...
Image image = Image.FromFile(Server.MapPath(String.Format("~/{0}.jpg", "YourImageNameHere")));
Graphics MyGraphic = Graphics.FromImage(LabelImage);
MyGraphic.DrawRectangle(SomePenObject, Point1, Point2, Point3, Point4);
Image.Save("C:\somepath.jpg",ImageFormat.Jpeg);

Categories

Resources