C# Slow Paint Event: painting large number of objects - c#

I have a PictureBox it serves as a canvas.
A List<RectangleObj> the array size of aprox 8000.
The "RectangleObj" is a simple rectangle class, once you invoke its Draw(Graphic g) method it will draw
the border using
g.DrawRectangle(...) and,
fill the rectangle with an alpha
transparency using
g.FillRectangle(...)
In the application Form.cs, i use the pictureBox1_Paint(...) to loop the array of RectangleObj and invoke the Draw method of that class.
Like this.
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < RectList.Count(); i++) //List<RectangleObj> count = 8000
RectList[i].Draw(e.Graphics);
}
Every time the mouse clicks upon a RectangleObj and drags changing its location (mouse move event) the paint event is called. since the array is large in number, the paint event does not have enough time to finish its loop and gets flooded with mouse movements. so, this makes the Paint event slow.
Can somebody advice me how to optimize this procedure.

Have you considered drawing to an in memory bitmap, then blitting that to the screen?

There are a couple of things here:
don't draw while moving. Calculate an outline for the selected elements and XOR only that outline when the mouse moves. Repaint on MouseUp.
don't draw stuff you don't need. You can run an algorithm to detect which rectangles are totally obscured and ignore them.
Make sure you have DoubleBuffered=true for your Picturebox

Work out which rectangles need to be redrawn based on the location of the moving rectangle and its prior location and only redraw those. Clip the painting to only those parts that have been invalidated.

Related

How should I buffer drawn rectangles to improve performance (C#/.NET/WinForms/GDI+)

What I'm doing
I am working on a C#/.NET 4.7.2/WinForms app that draws a significant number of filled rectangles on a form using Graphics.FillRectangle.
Currently, the rectangles are drawn in the form's Paint event. After all the rectangles are drawn, a crosshair is drawn based on mouse position.
Whenever the mouse moves, Invalidate is called on the form to force a repaint so that the crosshair appears in its new position.
The problem
This is inefficient because the rectangles don't change, only the crosshair position, yet the rectangles are being redrawn every time. The CPU usage during mouse move is significant.
What next
I believe that the solution to this problem is to draw the rectangles to a buffer first (outside of the Paint event). Then, the Paint event only needs to render the buffer plus draw a crosshair on top.
Since I am new to GDI+ and manual buffering, I am wary of going down the wrong track. Google searches reveal plenty of articles on manual buffering, but each article seems to take a different approach which adds to my confusion.
I would be grateful for suggested approaches that favour simplicity and efficiency. If there is an idiomatic .NET way of doing this — the way it's meant to be done — I'd love to know.
Here's a quick and easy solution that doesn't require any buffering. To replicate this, start with a fresh Windows Forms project. I only draw two rectangles, but you can have as many as you want.
If you create a new WinForms project with these two member variables and these two handlers, you will get a working sample.
First, a couple of member variables for your form:
private bool _started = false;
private Point _lastPoint;
The started flag will turn to true after the first mouse move. The _lastPoint field will track the point at which the last cross-hairs was drawn (that's mostly why _started exists).
The Paint handler will draw the cross hairs every time it's called (you'll see why this is ok with the MouseMove handler):
private void Form1_Paint(object sender, PaintEventArgs e)
{
var graphics = e.Graphics;
var clientRectangle = this.ClientRectangle;
//draw a couple of rectangles
var firstRectangle = clientRectangle;
firstRectangle.Inflate(-20, -40);
graphics.FillRectangle(Brushes.Aqua, firstRectangle);
var secondRectangle = clientRectangle;
secondRectangle.Inflate(-100, -4);
graphics.FillRectangle(Brushes.Red, secondRectangle);
//draw Cross-Hairs
if (_started)
{
//horizontal
graphics.DrawLine(Pens.LightGray, new Point(clientRectangle.X, _lastPoint.Y),
new Point(ClientRectangle.Width + clientRectangle.X, _lastPoint.Y));
//vertical
graphics.DrawLine(Pens.LightGray, new Point(_lastPoint.X, clientRectangle.Y),
new Point(_lastPoint.X, ClientRectangle.Height + clientRectangle.Y));
}
}
Now comes the MouseMove handler. It's where the magic happens.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
var clientRectangle = this.ClientRectangle;
var position = e.Location;
if (clientRectangle.Contains(position))
{
Rectangle horizontalInvalidationRect;
Rectangle verticalInvalidationRect;
if (_started)
{
horizontalInvalidationRect = new Rectangle(clientRectangle.X,
Math.Max(_lastPoint.Y - 1, clientRectangle.Y), clientRectangle.Width, 3);
verticalInvalidationRect = new Rectangle(Math.Max(_lastPoint.X - 1, clientRectangle.X),
clientRectangle.Y, 3, clientRectangle.Height);
Invalidate(horizontalInvalidationRect);
Invalidate(verticalInvalidationRect);
}
_started = true;
_lastPoint = position;
horizontalInvalidationRect = new Rectangle(clientRectangle.X,
Math.Max(_lastPoint.Y - 1, clientRectangle.Y), clientRectangle.Width, 3);
verticalInvalidationRect = new Rectangle(Math.Max(_lastPoint.X, clientRectangle.X - 1),
clientRectangle.Y, 3, clientRectangle.Height);
Invalidate(horizontalInvalidationRect);
Invalidate(verticalInvalidationRect);
}
}
If the cursor is within the form, I do a bunch of work. First I declare two rectangles that I will be using for invalidate. The horizontal one will be a rectangle that fills the width of the client rectangle, but is only 3 pixels high, centered on the Y coordinate of the area that I want to invalidate. The vertical one is as high as the client rectangle, but only 3 pixels wide. It's centered on the X coordinate of the area that I want to invalidate.
When the Paint handler runs, it virtually paints the entire client area, but only the pixels in the total invalidated area actually get drawn on the screen. Anything outside the invalidate area is left alone.
So, when the mouse moves, I create two rectangles (one vertical, one horizontal) that surround where the last set of cross-hairs were (so that when the pixels in those rectangles are drawn (including the background), the old cross-hairs are effectively erased) and then I create two new rectangles surrounding where the current cross-hairs should go (causing the background and the new cross-hairs to be drawn).
You are going to want to learn about invalidation rectangles if you have a complicated drawing app. For example, when the form is resized, what you want to do is invalidate only the newly unveiled rectangle(s), so that the whole drawing doesn't need to be rendered.
This works, but picking a color (or a brush) for the cross-hairs so that they always show can be difficult. Using my other suggestion (that you draw the lines twice (one to erase, one to draw) using an INVERT (i.e. XOR) brush is faster, and it always shows.

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..

c#:WindowsForms - performance optimization when redrawing bitmap

In my program I have a picture box, containing a bitmap.(300x300 35kB .PNG file)
If 2 variables(x/z coord) are changed, I draw a new circle every second to the new position accordingly - a timer runs in the background, invoking this method.
void DrawEllipse()
{
// Retrieve the image.
bChamber = new Bitmap(global::Project.Properties.Resources.driveChamber1);
gChamber = Graphics.FromImage(bChamber);
gChamber.FillEllipse(brushChamber, VirtualViewX(), VirtualViewY(), 10, 10);
pictureBoxDriveView.Image = bChamber;
}
Now I'm looking for ways to optimize the performance. Redrawing the pic every 0.2s e.g. slows the program so much, I cant do anything else.
But ultimately I need a more fluent movement of the circle, you can Imagine how it laggs with the 1000ms refresh rate.
Is there a better way to do this, then loading the whole bitmap every time?
Use the Controls the way they were intended.
do not redraw the Bitmap yourself.
just load it 1x in the Picturebox.
handle the Paint event of the picturebox to draw the ellipse
invalidate the Picturebox whenever your coords change.
Draw the circle ONE time in a control (PictureBox)
Put the control across the 300x300 picture box.
When, and only when, the variables change, update the location of the picturebox with the circle.
This way you prevent drawing too many times.
Try setting the DoubleBuffered property of the form to true. This generally results in improved performance.
Also, you should put this
// Retrieve the image.
bChamber = new Bitmap(global::Project.Properties.Resources.driveChamber1);
In the class constructor.
Try this, it does not load the image from disk every time, so it is less expensive.
private Image _origImage = new Bitmap(global::Project.Properties.Resources.driveChamber1);
void DrawEllipse()
{
// Retrieve the image.
Image bChamber = new Bitmap((Image)this._origImage.Clone());
Graphics gChamber = Graphics.FromImage(bChamber);
gChamber.FillEllipse(brushChamber, VirtualViewX(), VirtualViewY(), 10, 10);
pictureBoxDriveView.Image = bChamber;
}

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;
}

Controlling the visibility of a Bitmap in .NET

I am trying to create this simple application in c#: when the user double clicks on specific location in the form, a little circle will be drawn. By one click, if the current location is marked by a circle - the circle will be removed.
I am trying to do this by simply register the MouseDoubleClick and MouseClick events, and to draw the circle from a .bmp file the following way:
private void MouseDoubleClick (object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
Bitmap myImage = (Bitmap)Bitmap.FromFile("Circle.bmp");
g.DrawImage(myImage, e.X, e.Y);
}
My problem is that I dont know how to make the circle unvisible when the user clicks its location: I know how to check if the selected location contains a circle (by managing a list of all the locations containig circles...), but I dont know how exactly to delete it.
Another question: should I call the method this.CreateGraphics() everytime the user double-clicks a location, as I wrote in my code snippet, or should I call it once on initialization?
My personal preference is to put my images in instances of the Picturebox class. Reason being, I can simply call each Picturebox's Hide() function (or set 'Visible` to false).
What you're doing is drawing directly onto the window's client area, which technically isn't wrong but normally should be done in the form's Paint handler. If at some point you decide you don't want your circle to be visible anymore, you can call the form's Invalidate() method which triggers the Paint event. There, you explicitly do not draw your circle, and so to the user, the circle disappears.
The nice thing about a Picturebox is that it's persistent - you put your image into it and optionally draw on that image, but you only need to draw once. If you use the Paint handler technique, your drawing code gets called each time the form needs to redraw itself.
Edit:
Here's some code that illustrates my Paint handler information:
private void Form_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(); // clear any and all circles being drawn
if (CircleIsVisible)
{
e.Graphics.DrawEllipse( ... ); // OR, DrawImage( ) as in your example
}
}
private void MouseDoubleClick (object sender, MouseEventArgs e)
{
CircleIsVisible = true;
Invalidate(); // triggers Paint event
}
If you're drawing bitmaps, I would load the bitmap once and store it as a class variable. This way you don't need to hit the hard drive each time you want to draw. Dispose of the bitmap when you dispose of your class (in this case, your window).
I thinks you should clear all of the image you draw before your next double click.
Such as Graphics.Clear().
On the other hand, you should not to create Graphics object or dispose it every time.
If you have simple background color you could use Graphics.DrawEllipse to draw Circles and then just change circle color to the background color. Also you need to have a Collection of all circles you draw so you can access any circle that you've drawn.

Categories

Resources