Improving perfomance for randomly created panels - c#

So what I'm trying to do is create like a random image from panels of different colors. The user can choose how many panels (i.e. pixels) he wants to have and the number of different colors and then the program automatically generates that image. I'd really like to use panels for this because I will need this picture later on and need to modify every single pixel. As I'm comfortable with panels, I'd like to keep them and not use anything else.
So here's the code I'm using to create this panels:
//Creates two lists of panels
//Add items to list so that these places in the list can be used later.
//nudSizeX.Value is the user-chosen number of panels in x-direction
for (int a = 0; a < nudSizeX.Value; a++)
{
horizontalRows.Add(null);
}
//nudSizeY.Value is the user-chosen number of panels in y-direction
for (int b = 0; b < nudSizeY.Value; b++)
{
allRows.Add(null);
}
for (int i = 0; i < nudSizeY.Value; i++)
{
for (int j = 0; j < nudSizeX.Value; j++)
{
// new panel is created, random values for background color are assigned, position and size is calculated
//pnlBack is a panel used as a canvas on whoch the other panels are shown
Panel pnl = new Panel();
pnl.Size = new System.Drawing.Size((Convert.ToInt32(pnlBack.Size.Width)) / Convert.ToInt32(nudSizeX.Value), (Convert.ToInt32(pnlBack.Size.Height) / Convert.ToInt32(nudSizeY.Value)));
pnl.Location = new Point(Convert.ToInt32((j * pnl.Size.Width)), (Convert.ToInt32((i * pnl.Size.Height))));
//There are different types of panels that vary in color. nudTypesNumber iis the user-chosen value for howmany types there should be.
int z = r.Next(0, Convert.ToInt32(nudTypesNumber.Value));
//A user given percentage of the panels shall be free, i.e. white.
int w = r.Next(0, 100);
if (w < nudPercentFree.Value)
{
pnl.BackColor = Color.White;
}
//If a panel is not free/white, another rendom color is assigned to it. The random number determinig the Color is storede in int z.
else
{
switch (z)
{
case 0:
pnl.BackColor = Color.Red;
break;
case 1:
pnl.BackColor = Color.Blue;
break;
case 2:
pnl.BackColor = Color.Lime;
break;
case 3:
pnl.BackColor = Color.Yellow;
break;
}
}
//Every panel has to be added to a list called horizontal rows. This list is later added to a List<List<Panel>> calles allRows.
horizontalRows[j] = (pnl);
//The panel has also to be added to the "canvas-panel" pnl back. The advantage of using the canvas panel is that it is easier to determine the coordinates on this panel then on the whole form.
pnlBack.Controls.Add(pnl);
}
allRows[i] = horizontalRows;
}
As you might imagine, this is very slow when creating a checkerboard of 99x99 because the program has to loop through the process nearly 10000 times.
What would you to to improve performance? I said I'd like to keep doing it with panels because I'm comfortable with them, but if using panels is even more dumb than I thought, I'm open to other options. The program gets slower and slower the more panels it has already created. I guess that's because of the adding to the list that grows larger and larger?
This is how the output looks right now:
This is what I want to do with my "picture" later: I basically want to do Schellings model. That model shows how different groups of people (i.e. different colors) segregate when they want to have a certain percentage of people around them that belong to their group. That means that later on I have to be able to check for each of the panels/pixels what the neighbours are and have to be able to be able to change color of each pixel individually.
I don't want a ready solution, I'm just hoping for tips how to improve the speed of the picture-creating process.
Thank you very much

Instead of using Panels use a matrix to store your colors and other information you need.
In OnPaint event, use this matrix to draw the rectangles using GDI+.
Here is an example on how to draw 10x10 "pixels" if you have a matrix that contains colors:
private void myPanel_Paint(object sender, PaintEventArgs e)
{
for (var y=0; y < matrix.GetUpperBound(0); y++)
for (var x=0; x < matrix.GetUpperBound(1); x++)
{
var Brush = new SolidBrush(matrix[y,x]);
e.Graphics.FillRectangle(Brush, new Rectangle(x*10, y*10, 10, 10));
}
}

Use a picturebox to do your drawing. You've already got the code to see where each panel should be, just change it to draw a rectangle at each position. This way, you'll just be drawing a few rectangles on a board instead of working with 10.000 GUI objects.
Oh, keep your model/logic and view separated. Keep one matrix with all your information and just use a "Paint method" to draw it.
Your model could look something like this:
MyPanel[,] panels;
class MyPanel
{
Color color;
}
This way it's easy to check all neighbours of a panel, just check in the panels matrix.
And your view should just do something like this:
class View
{
Paint(MyPanel[,] panels)
{
//Draw
}
}

I think your best approach here is to write a custom Control class to draw the squares, and a custom collection class to hold the squares.
Your square collection class could look like this:
public sealed class ColouredSquareCollection
{
readonly int _width;
readonly int _height;
readonly Color[,] _colours;
public ColouredSquareCollection(int width, int height)
{
_width = width;
_height = height;
_colours = new Color[_width, _height];
intialiseColours();
}
public Color this[int x, int y]
{
get { return _colours[x, y]; }
set { _colours[x, y] = value; }
}
public int Width
{
get { return _width; }
}
public int Height
{
get { return _height; }
}
void intialiseColours()
{
for (int y = 0; y < _height; ++y)
for (int x = 0; x < _width; ++x)
_colours[x, y] = Color.White;
}
}
Then you write a custom control. To do so, add a new Custom control via Add new item -> Windows Forms -> Custom Control, and call it ColouredSquareHolder.
Then change the code to look like this. Notice how it is responsible for drawing all the squares:
public sealed partial class ColouredSquareHolder: Control
{
ColouredSquareCollection _squares;
public ColouredSquareHolder()
{
ResizeRedraw = true;
DoubleBuffered = true;
InitializeComponent();
}
public ColouredSquareCollection Squares
{
get
{
return _squares;
}
set
{
_squares = value;
Invalidate(); // Redraw after squares change.
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (_squares == null)
return;
int w = Width;
int h = Height;
int nx = _squares.Width;
int ny = _squares.Height;
var canvas = pe.Graphics;
for (int yi = 0; yi < ny; ++yi)
{
for (int xi = 0; xi < nx; ++xi)
{
int x1 = (xi*w)/nx;
int dx = ((xi + 1)*w)/nx - x1;
int y1 = (yi*h)/ny;
int dy = ((yi+1)*h)/ny - y1;
using (var brush = new SolidBrush(_squares[xi, yi]))
canvas.FillRectangle(brush, x1, y1, dx, dy);
}
}
}
}
Now you'll need to set up the square collection, add it to a ColouredSquareHolder and then add that to a form.
Firstly, add the ColouredSquareHolder to your test program and compile it so that it will show up in the Toolbox for the Windows Forms Editor.
Then create a new default Form called Form1, and from the Toolbox add a ColouredSquareHolder to it, and set the ColouredSquareHolder to Dock->Fill. Leave it called the default colouredSquareHolder1 for this demonstration.
Then change your Form1 class to look like this:
public partial class Form1: Form
{
readonly ColouredSquareCollection _squares;
readonly Random _rng = new Random();
public Form1()
{
InitializeComponent();
_squares = new ColouredSquareCollection(100, 100);
for (int x = 0; x < _squares.Width; ++x)
for (int y = 0; y < _squares.Height; ++y)
_squares[x, y] = randomColour();
colouredSquareHolder1.Squares = _squares;
}
Color randomColour()
{
return Color.FromArgb(_rng.Next(256), _rng.Next(256), _rng.Next(256));
}
}
Run your program and see how much faster it is at drawing the squares.
Hopefully this will give you the basis for something that you can build on.
Note: If you change the colours in the square collection, you will need to call .Invalidate() on the control in the form to make it redraw with the new colours.

well I suggest you using GDI+ instead , you can store your colors in a 2 dimensional array so you can draw the desired image based on that and also you can loop through them for further process , take a look at this code and also the demo project :
as you mentioned that you're not familiar with gdi+ , there is a demo project included so you can check it yourself and see how It's done in gdi+ :
demo project : ColorsTableDemoProject
Color[,] colorsTable;
Bitmap b;
Graphics g;
int size = 80; // size of table
int pixelWidth = 5; // size of each pixel
Random r = new Random();
int rand;
// CMDDraw is my Form button which draws the image
private void CMDDraw_Click(object sender, EventArgs e)
{
colorsTable = new Color[size, size];
pictureBox1.Size = new Size(size * pixelWidth, size * pixelWidth);
b = new Bitmap(size * pixelWidth, size * pixelWidth);
g = Graphics.FromImage(b);
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
rand = r.Next(0, 4);
switch (rand)
{
case 0: colorsTable[x, y] = Color.White; break;
case 1: colorsTable[x, y] = Color.Red; break;
case 2: colorsTable[x, y] = Color.Blue; break;
case 3: colorsTable[x, y] = Color.Lime; break;
default: break;
}
g.FillRectangle(new SolidBrush(colorsTable[x, y]), x * pixelWidth, y * pixelWidth, pixelWidth, pixelWidth);
}
}
pictureBox1.Image = b;
}

Related

WPF Display a portion of bigger image in ImageBox

I'm coming from Winforms trying to rewrite a program in WPF, and I want to display a certain portion of the whole image, depending on an Id I use for a list, that I load each portion of the whole image in. I was able to do it successfully in Winforms, but I want to perform the same task in WPF using Controls.Image. Heres what I did in Winforms.
PictureBox picBox;
List<Image> tileImageList;
Image FullImage;
public TileFrame(PictureBox pbox)
{
picBox = pbox;
FullImage = picBox.Image; //The source of the picBox is set to the full image on init
tileImageList = new List<Image>();
PopTileList();
}
void PopTileList()
{
const int SIZE = 32;
Bitmap bitFullImage = new Bitmap(FullImage);
for (int y = 0; y < 48; y++)
{
for (int x = 0; x < 64; x++)
{
var portion = bitFullImage.Clone(new Rectangle((x * SIZE), (y * SIZE), SIZE, SIZE), bitFullImage.PixelFormat);
tileImageList.Add(portion);
}
}
picBox.Image = tileImageList[10];//The first image that shows when this is done
}
public void ShowTilePic(int selectedId)
{
picBox.Image = tileImageList[--selectedId];
}
Since the image being displayed will change based on the selected item of a listbox, the tileImageList is crucial for relating the list box selected index and the tileImageList index. Other answers I've searched for seemed to make it much more complicated than what I've done here. Is there a simple way to do this in WPF and in code?
Nvm I figured it out.
List<CroppedBitmap> tileImageList;
Image imageBox;
public TileFrame(MainWindow mWindow)
{
tileImageList = new List<CroppedBitmap>();
imageBox = mWindow.ImageBox;
PopTileList();
}
void PopTileList()
{
const int SIZE = 32;
var bitmapImage = (BitmapSource)imageBox.Source;
for (int y = 0; y < 48; y++)
{
for (int x = 0; x < 64; x++)
{
var portion = new CroppedBitmap(bitmapImage, new Int32Rect((x * SIZE), (y * SIZE), SIZE, SIZE));
tileImageList.Add(portion);
}
}
}
public void ShowTilePic(int selectedId)
{
imageBox.Source = tileImageList[selectedId];
}

Matrix of photos

So I have a code that injects an image into my project through resources Image foodWorld = Resources.orange and I want to make a matrix out of this photo, so it can look like this:
I have this code but I don't know how to draw the matrix. Also, I don't know if this is the right way to draw it or not:
this.Width = 400;
this.Height = 300;
Bitmap b = new Bitmap(this.Width, this.Height);
for(int i = 0; i < this.Height; i++)
{
for(int j = 0; j < this.Width; j ++)
{
//fill the matrix
}
}
I am not too familiar with WinForms, but in WPF, I'd do it this way:
var columns = 15;
var rows = 10;
var imageWidth = 32;
var imageHeight = 32;
var grid = new Grid();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
//Get the image in your project; I'm not sure how this is done in WinForms
var b = new Bitmap(imageWidth, imageHeight);
//Display it
var pictureBox = new PictureBox();
pictureBox.Image = b;
//Set the position
Grid.SetColumn(j, pictureBox);
Grid.SetRow(i, pictureBox);
//Insert into the "matrix"
grid.Children.Add(pictureBox);
}
}
For moving Pacman, repeat the above, but for only one image. Store a reference to the current position and when certain keys are pressed,
Animate it's margin until it appears to be in an adjacent cell (for instance, if each cell is 16 pixels wide and pacman should be in the center of any given cell, animate the right margin by 16 pixels to get it into the cell on the right and so forth).
Once it has moved to another cell, set the new row and column based on the direction in which it last moved.
If there is a fruit at the new position, get the fruit at that position and remove it from the Grid. You can get it by using myGrid.Children[currentRow * totalColumns + currentColumn] assuming currentRow and currentColumn are both zero-based.
Repeat for each cell it must move to.
This does mean the matrix will have a fixed size, but in WPF, there is a Viewbox, which is convenient for these types of scenarios. Also, set the z-index of pacman to be greater than the fruits so it's always on top.

Highlighting potential position of dynamic control in c#

I have created application where user can drag and drop the controls during run-time. I use my ss function to align the controls in a table like fashion using 2D-array. I want the application to show/highlight the position where the control will be placed when its brought near certain coordinate.
struct IconPanel
{
public int left;
public int top;
}
static void ss(Control control)
{
int row, col, nearestCol = 0, nearestRow = 0, rowDist = 100, diff, colDist = 100;
for (row = 0; row < iconPanels.GetLength(0); row++)
{
for (col = 0; col < iconPanels.GetLength(1); col++)
{
diff = Math.Abs(control.Left - iconPanels[row, col].left);
if (diff < colDist)
{
colDist = diff;
nearestCol = col;
}
diff = Math.Abs(control.Top - iconPanels[row, col].top);
if (diff < rowDist)
{
rowDist = diff;
nearestRow = row;
}
}
}
control.Left = iconPanels[nearestRow, nearestCol].left;
control.Top = iconPanels[nearestRow, nearestCol].top;
}
You probably don't want these position markers to persist, so this is one of the rare cases where I would use
using ( Graphics G = theParentContainer.CreateGraphics())
foreach(Rectangle rect in yourPositions) G.DrawRectangle(Pens.Red, rect);
Clean them up after the drop or after leaving the control etc.. by calling theParentContainer.Invalidate();
This assumes that you know the possible position and can create a
List<Rectangle> yourPositions = new List<Rectangle>();
holding them.
As we all know ;-) graphics created with a Graphics object that was instantiated with Control.CeateGraphics won't persist and will dissappear with the next Paint event. But for such an interactive helper graphics this is perfect. Other examples are rubberband-drawing or cursor tracking..
On control that you would like to be highlited subscribe to Paint event.
private void highlightControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) {
if(mouse is over or other control is over) {
Graphics g = e.Graphics;
g.FillRectangle(Brushes.Red, 0, 0, this.Width, this.Height);
}
}

Issue with mouse clicking a rectangle in an array

So, I'm attempting to create a grid on the screen, and to do so, I've implemented a multidimensional array of Rectangles.
When the program starts, I use a for loop to increase the x and y coordinates to form the grid.
public Form1() {
InitializeComponent();
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 12; y++) {
recArray[x, y] = new Rectangle(y * 50, x * 50, 100, 100);
}
Application.DoEvents();
}
}
My issue is trying to figure out when the user has clicked on a rectangle, and furthermore, which rectangle in the array that he/she has clicked on. As I will change the border to red when given the correct rectangle.
I'm using Visual Studio 2008, and here is my code so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Quoridor {
public partial class Form1 : Form {
private Pen pen = Pens.Black;
Rectangle[,] recArray = new Rectangle[12, 12];
public Form1() {
InitializeComponent();
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 12; y++) {
recArray[x, y] = new Rectangle(y * 50, x * 50, 100, 100);
}
Application.DoEvents();
}
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 12; y++) {
e.Graphics.DrawRectangle(pen, recArray[x, y]);
Application.DoEvents();
}
}
}
private void Form1_Click(object sender, EventArgs e) {
Point cursor = this.PointToClient(Cursor.Position);
Refresh();
}
}
}
I'm making this into a real game, with classes and all. But keep in mind, this is my second month programming, so don't be harsh ^_^
First, a couple of pointers:
You are storing your calculated y coordinate as the x position of your rectangle and vice versa. Switch the first two arguments of the Rectangle constructor to resolve this.
Use the MouseClick event instead of the Click event. The former provides you with a MouseEventArgs that contains the coordinate of the click relative to your Form.
Your rectangles are currently overlapping, since they are 100 x 100 but are positioned 50 pixels apart. This appears to be unintended (as a click would then usually land on 2 rectangles). This is also why your grid appears to be 13x13 instead of 12x12. To resolve this, pass 50 instead of 100 as the width and height of your Rectangles.
You could then determine the clicked Rectangle as follows:
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
Rectangle clickedRectangle = FindClickedRectangle(e.Location);
if (!clickedRectangle.IsEmpty)
Console.WriteLine("X: {0} Y: {1}", clickedRectangle.X, clickedRectangle.Y);
}
private Rectangle FindClickedRectangle(Point point)
{
// Calculate the x and y indices in the grid the user clicked
int x = point.X / 50;
int y = point.Y / 50;
// Check if the x and y indices are valid
if (x < recArray.GetLength(0) && y < recArray.GetLength(1))
return recArray[x, y];
return Rectangle.Empty;
}
Notice that I determine the clicked rectangle using a straightforward calculation, which is possible because your rectangles are positioned in a grid. If you intend to depart from the grid layout, looping over all rectangles and hit testing them using Rectangle.Contains(Point) is an alternative solution.

map maker application

I have created a somewhat complete application which allows me to create a map (.txt file with information about all the points of the map), load it and draw it.
My solution for this was, inside the windows forms application, to put a panel (since I need to be able to move on map) and inside that panel pictureboxes(since I want to put a background image and image on them) that represent points of map in size 50x50 pixels. The problem I am facing now is increased load time for my application, since I am loading pictures into the pictureboxes...
Does anyone have any alternative suggestion to what I have been attempting?
Visual representation might help:
The code, as requested: (well, some of it)
private void Load_Map()
{
for (int i = Y - 12; i < Y + 12; i++)
{
if ((i >= 0) & (i < Int32.Parse(MP.Mheight)))
{
string Line = xline[i];
for (int j = X - 12; j < X + 12; j++)
{
if ((j >= 0) & (j < Int32.Parse(MP.Mwidth)))
{
int X = i * Int32.Parse(MP.Mwidth) + j;
int Z = Int32.Parse(Line[j].ToString());
Map_Location[X] = Z;
Color H = new Color();
Map_Point(j, i, Map_Height(Z, H), 50);
}
}
}
}
}
Creating points:
private void Map_Point(int X, int Y, Color H, int Point_Size)
{
PictureBox MP = new PictureBox();
MP.Name = Map_Coordinates(X, Y);
MP.Size = new Size(Point_Size, Point_Size);
MP.Location = new Point(Y * (Point_Size + 1) + 4, X * (Point_Size + 1) + 4);
MP.BackColor = H;
Control MW = this.Controls["WorldMap"];
MW.Controls.Add(MP);
}
You'll be better off creating a custom control by deriving from System.Windows.Forms.Control and overriding the OnPaint method and doing your own drawing and handling click events yourself.
Using a large number of WinForms controls the way you're doing is an exercise in pain, as WinForms will create a hWnd object for each control, and WinForms doesn't scale too well, unfortunately.
You should be using System.Drawing.Graphics
Here are the MSDN Tutorials for it.
It has a method called DrawImage , which you can use instead of a picture box. For the grid you should be drawing it as a rectangle with a color for the background and vertical/horizontal lines to make the grid.

Categories