troubleshooting Question

Can I make short GDI+ code in csharp c# code more efficient ??

Avatar of yaronusa
yaronusa asked on
.NET ProgrammingC#Game Programming
18 Comments1 Solution913 ViewsLast Modified:
I need to know how to make the short code snippet more efficient.

There is an inner and outer loop, and basically the code draws squares, one next to the other. Then it figures out if it should draw two more lines (in form of a cross), and if it should draw one last triangle. Most of the work is done inside the two loops though.

When the code draws a grid of 200 by 200 squares, it's good. It can even draw a grid 350 by 350 squares (122500 squares), but with a little over 1 second delay.

Anything simple I can do to improve this??? :) Thanks!
protected override void OnPaint(PaintEventArgs e)
            Graphics g = e.Graphics;
            g.FillRectangle(Brushes.White, this.ClientRectangle);
            int cellHeight = this.CellHeight * this.Zoom;
            int cellWidth = this.CellWidth * this.Zoom;
            int nbrColumns = this.Columns;
            int nbrRows = this.Rows;
            Size scrollOffset;
            // Get negative x & y coordinates of scroll
            scrollOffset = new Size(this.AutoScrollPosition);
            // Draw cells
            for (int row = 0; row < nbrRows; row++)
                for (int col = 0; col < nbrColumns; col++)
                    Point cellLocation = new Point(col * cellWidth + scrollOffset.Width, 
                                                   row * cellHeight + scrollOffset.Height);
                    // Define cell parameter
                    Rectangle cellRect = new Rectangle(cellLocation.X,
                                                       cellWidth, cellHeight);
                    // Only draw cell if it needs to be painted
                    if (cellRect.IntersectsWith(e.ClipRectangle))
                        g.FillRectangle(new SolidBrush(
                                _grid.getFillColor(col, row)), cellRect);
                        g.DrawRectangle(new Pen(
                                _grid.getBorderColor(col, row), 1), cellRect);
Jaime Olivares
Software Architect
Join our community to see this answer!
Unlock 1 Answer and 18 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 18 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros