Make Square Rectangles in a fixed Square Picturebox like a grid - c#

I am working on a project using c# and visual studio(.NET Framework) in which the user can interact with some square boxes arranged in a grid using a PictureBox. The default size will be 20 x 20
The user can change the number of squares in the PictureBox but the size of the PictureBox should remain the same. I use WinForms.
The code that I have tried by using my logic and some of the internet's, I get it working as a square grid with squares in them, but as I increase the xNum or yNum, the grid starts becoming smaller and smaller. Here is my function which performs the drawing of rectangles:
public Graphics CreateRectangles(int xNum, int yNum, Graphics g)
{
rectList.Clear();
int width = (pictureBox1.Image.Height / xNum) - 1;
int height = (pictureBox1.Image.Height / yNum) - 1;
int both = (width + height) / 2;
Rectangle rect = new Rectangle();
rect.Size = new Size(both, both);
for(int x = 0; x < xNum; x++)
{
rect.X = x * rect.Width;
for(int y = 0; y < yNum; y++)
{
rect.Y = y * rect.Height;
rectList.Add(rect);
}
}
pictureBox1.Refresh();
foreach (Rectangle rec in rectList)
{
Pen p = new Pen(Color.Blue);
g.DrawRectangle(p, rec);
}
g.DrawLine(new Pen(Color.Blue), 0, yNum * height, xNum * width, yNum * height);
return g;
}
I clear the screen whenever I want to draw by
pictureBox1.Image = new Bitmap((Screen.PrimaryScreen.Bounds.Width / 8) * 7, (Screen.PrimaryScreen.Bounds.Height / 8) * 7);
Please help me fix the issue so that the size of the square area in the pictureBox1 remains the largest it can be without overlapping other GUI Elements.
Thanks In Advance. 👍
EDIT:
I know that if I have relative sizes then the cell size will go down, but that'
s expected behaviour, But I don't want the whole frame of the table to go down in size, As when I increase the xNum, the size of the outer frame/box should remain same

Related

How to increase the height of curve in windows forms

I want to increase the height of the curve but its left and right position should remain same. Just want to lift up from center to give it a shape like curve as height changes.
Pen blackPen = new Pen(Color.Black, 3);
// Create coordinates of rectangle to bound ellipse.
int x = 93;
int y = 136;
int width = 320;
int height = 50;
// Create start and sweep angles on ellipse.
int startAngle = 0;
int sweepAngle = -180;
// Draw arc to screen.
e.Graphics.DrawArc(blackPen, x, y, width, height, startAngle, sweepAngle);
In the most direct way your problem can be solved like this:
int change = 0;
e.Graphics.DrawArc(blackPen, x, y-change, width, height+change, startAngle, sweepAngle);
By increasing the variable change the ellipse will curve up more and more:
private void button1_Click(object sender, EventArgs e)
{
change += 10;
panel1.Invalidate();
}
But maybe you want more control over the shape? Let's have a look at the options:
Here are examples of the three 'curve' drawing methods:
Curves, Beziers & Ellipses
And here is the code to draw that image.
Please ignore the Graphics.xxxTransform calls! They only are meant to shift the curves a little bit upwards so they don't overlap too much to see them properly.
Also note that the curves in the first image are not completely convex. See the last part of the answer to see a DrawCurve call that avoids the concave segments!
The important part are the Points! And just as the comments suggest, in the third part the ellipses are being changed by making the height larger and moving the top of the Rectangle up by the same amount.
The complexity DrawArc of and DrawCurve is pretty much equal; both are controlled by four integers with a rather clear meaning: They either make one rectangle or the corners of a symmetrical triangle. (Plus one counterpoint for the convex call.)
DrawBezier is more complex, especially since the controls point(s) are not actually on the resulting curve. They can be thought of force vectors that pull the line into a curved shape and are harder to calculate.
private void panel1_Paint(object sender, PaintEventArgs e)
{
Point a = new Point(0, 200);
Point c = new Point(200, 200);
for (int i = 0; i< 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point b = new Point(100, 50 + i * 10);
e.Graphics.DrawCurve(Pens.Maroon, new[] { a, b, c }, 0.7f);
}
e.Graphics.ResetTransform();
Point pa = new Point(250, 200);
Point pb = new Point(450, 200);
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point pc = new Point(350, 200 - i * 10);
e.Graphics.DrawBezier(Pens.ForestGreen, pa, pc, pc, pb);
}
e.Graphics.ResetTransform();
int x = 500;
int y0 = 200;
int w = 200;
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Rectangle rect = new Rectangle(x, y0 - i * 10, w, 10 + i * 10);
e.Graphics.DrawArc(Pens.DarkBlue, rect, -0, -180);
}
e.Graphics.ResetTransform();
}
Notes:
The Curve (1st image) can be further controlled by the Tension parameter. The lower the tension the more pointed it gets, approaching 1f it makes the curve broader..
The Bezier curve (2nd image) is using only one control point. (Twice.) The curve gets a little pointed this way. You can make it broader and broader by using two different points the move apart little by little..
The Ellipse can't be controlled; it will always fill the bounding Rectangle.
Here is an example of varying the Curves and the Beziers:
The Curves are drawn with varying Tensions. Also I have used an overload that helps to get rid of the concave part at the start and end of the curve. The trick is to add a suitable extra point to the start and end and to tell the DrawCurve to leave out these 1st and last segments.
The simplest point to use (for both ends actually) is the counterpoint of the one at the top.
The Beziers are drawn using two control points, moving out and up a little.
Here is the code for the variations:
Point a = new Point(0, 200);
Point c = new Point(200, 200);
for (int i = 1; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point b = new Point(100, 50);
Point b0 = new Point(b.X, a.Y + (a.Y - b.Y));
e.Graphics.DrawCurve(Pens.Maroon, new[] { b0, a, b, c, b0 }, 1, 2, 0.1f * i);
}
e.Graphics.ResetTransform();
Point pa = new Point(250, 200);
Point pb = new Point(450, 200);
for (int i = 0; i < 10; i++)
{
e.Graphics.TranslateTransform(0, -5);
Point ca = new Point(350 - i * 9, 100 - i * 5);
Point cb = new Point(350 + i * 9, 100 - i * 5);
e.Graphics.DrawBezier(Pens.ForestGreen, pa, ca, cb, pb);
}
e.Graphics.ResetTransform();
here was the solution just increase value of y0 as u increase the value of
y0-i here i=20
int x = 96;
int y0 = 260;
int w = 320;
e.Graphics.TranslateTransform(0, -5);
Rectangle rect = new Rectangle(x, y0 - 20 * 10, w, 10 + 20 * 10);
e.Graphics.DrawArc(Pens.DarkBlue, rect, -0, -180);
e.Graphics.ResetTransform();

How to Draw Series of Numbers in every line (cols and rows) of Grid in PictureBox

just wanna ask if How can I draw series of Numbers for every line of grid col and rows ...
can also be by use of label ...
something like this:
http://oi60.tinypic.com/aeblth.jpg
heres my code as for now for Grid of PictureBox:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int numOfCells = 200;
int cellSize = 5;
Pen p = new Pen(Color.Black);
for (int y = 0; y < numOfCells; ++y)
{
g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
}
for (int x = 0; x < numOfCells; ++x)
{
g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
}
}
Note that numbers in the bottom and right of chart Position and count
are depends on count and position of line of grid in picture .
thanks for the help . more power!
First you have to create a block of X and Y. In the given screen shot the block of Y is about 10 and the block of X is about 2. To create the block of axes you need maximum and minimum value of graph.
NOTE: This is not a complete example. This is just a logic to understand how you can draw graph line.
int iXMin = 0;
int iXMax = 52;
int iYMin = 49890;
int iYMax = 50000;
Then you should create the size of block.
int iXSize = 26;
int iYSize = 12;
Single fXBlock = (iXMax - iXMin) / iXSize;
Single fYBlock = (iYMax - iYMin) / iYSize;
Now, You will require a method to convert axes position into pixel position.
This method is used to get the point of axes.
Single fXPxlSize = (pic.ClientRectangle.Width / (iXMax-iXMin))); //Getting X pixle size between two value.
Single fYPxlSize = (pic.ClientRectangle.Height / (iYMax-iYMin)); //Getting Y pixle size between two value.
Now, You can point out the value in the PictureBox.
Suppose you have first value XValue=0,YValue=50000 then you can get pixel position by using following formula.
int iX = Convert.ToInt32((XValue - XMin) * fXPxlSize);
int iY = Convert.ToInt32((YValue - YMin) * fYPxlSize);
Point p = New Point(iX,iY);
Create two List then add all those points one by one into the list. First is used to draw Cyan Line and Second is used to draw Yellow Line
List<Point> lstPointsC = new List<Point>(); //Declaration should be class level.
List<Point> lstPointsY = new List<Point>(); //Declaration should be class level.
lstPointsC.Add(p);
if (lstPointsY.Count > 0)
lstPointsY.Add(new Point(iX, lstPointsY[lstPointsY.Count].Y));
lstPointsB.Add(p);
Create code for Lines.
Graphics g = pic.CreateGraphics(); //you can also use e.Graphics from pic_paint event.
g.DrawLines(Pens.Cyan, lstPointsC.ToArray());
g.DrawLines(Pens.Yellow, lstPointsY.ToArray());
This method is used to draw custom line graph in your own control or form. But, I would like to suggest you use any third party tool like Crystal Report or Devexpress Charts.

In my heatmap graphing component, the y-axis time text does not exactly align

I have a method that takes in a bitmap, width, height, and a list of strings, overlays it on top of a black background, and adds y-axis text onto it (as demonstrated in the picture below).
In my attempt to align the text so they occupy the exact vertical space of my graph, I took the height and divided it by the number of values in the list:
float verticalDistance = height / times.Count;
However, perhaps of alignment issues, the space between each time value on the y-axis doesn't fix exactly into the height of the original bitmap, which is the variable height.
I thought it was an issue with int and it rounding numbers up or down, but changing it verticalDistance to a float did not ameliorate the issue.
private Bitmap overlayBitmap(Bitmap sourceBMP, int width, int height, List<String> times) {
int newWidth = width + (width / 3);
int newHeight = height + (height / 3);
Bitmap result = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(result)) {
g.FillRectangle(Brushes.Black, 0, 0, newWidth, newHeight);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
StringFormat stringFormatX = new StringFormat();
stringFormatX.LineAlignment = StringAlignment.Center;
Font drawFontX = new Font("Whitney", 10);
float verticalDistance = height / times.Count;
for (int i = 0; i < times.Count; i++) {
if (i % 5 == 0) {
g.DrawString(times[i], drawFontX, Brushes.White, 5, ((newHeight - height)/2) + (verticalDistance * i), stringFormatX);
}
}
g.DrawImage(sourceBMP, width / 6, height / 6, width, height);
}
return result;
}
What could be the issue here?
Reduce your problem to the simplest case: What if you had just two values to display on your Y axis? Your vertical distance would be the length of the axis. Your vertical distance formula would not work in that case. Therefore
float verticalDistance = height / (times.Count - 1.0);

XNA - Culling Performance Issue

This method that draws my tiles seems to be quite slow, Im not sure exactly whats wrong, it belive my culling method isnt working and is drawing stuff offscreen, but im not completeley sure. Here it is:
// Calculate the visible range of tiles.
int left = (int)Math.Floor(cameraPosition.X / 16);
int right = left + spriteBatch.GraphicsDevice.Viewport.Width / 16;
right = Math.Min(right, Width) + 1; // Width -1 originally - didn't look good as tiles drawn on screen
if (right > tiles.GetUpperBound(0))
right = tiles.GetUpperBound(0) + 1; // adding 1 to get the last right tile drawn
int top = (int)Math.Floor(cameraPosition.Y / 16);
int bottom = left + spriteBatch.GraphicsDevice.Viewport.Height/ 16;
bottom = Math.Min(bottom, Height) + 1; // Height -1 originally - didn't look good as tiles drawn on screen
if (bottom > tiles.GetUpperBound(1))
bottom = tiles.GetUpperBound(1) + 1; // adding 1 to get the last bottom tile drawn
// For each tile position
for (int y = top; y < bottom; ++y)
{
for (int x = left; x < right; ++x)
{
// If there is a visible tile in that position, draw it
if (tiles[x, y].BlockType.Name != "Blank")
{
Texture2D texture = tileContent["DirtBlock_" + getTileSetType(tiles,x,y)];
spriteBatch.Draw(texture, new Vector2(x * 16, y * 16), Color.White);
if (isMinimap)
spriteBatch.Draw(pixel, new Vector2(30+x, 30+y), Color.White);
}
}
}
GetTileSetTypes is a function to get what tiles are around it, for different textures, like DirtBlock_North, DirtBlock_Center, etc.
Tile content is just a class with my block textures.
Try changing SpriteBatch.Begin to defered and combining all of the tiles onto one texture.
See this GameDev question for info about why deferred is most likely the fastest option for you.
Also realize that every time you draw a new texture you have to take the old one out of the GPU and put the new one in. This process is called texture swapping and usually isn't an issue but you are swapping textures twice per tile which is likely to impact performance noticeably.
This can be fixed by combining multiple sprites onto one texture and using the source rectangle argument. This allows you to draw multiple sprites without a texture swap. There are a few OSS libraries for this. Sprite Sheet Packer is my personal favorite.
Unfortunantly without the project and a profiler I'm just guessing; however, these are the two biggest gotchas for rendering tilemaps I know of. I can't really see anything wrong from here. Below is the code I use to draw my tile maps and as you see its very similar to yours.
If all else fails I would suggest using a profiler to figure out which bits are running slowly.
//Init the holder
_holder = new Rectangle(0, 0, TileWidth, TileHeight);
//Figure out the min and max tile indices to draw
var minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0);
var maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width);
var minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0);
var maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height);
for (var y = minY; y < maxY; y++) {
for (var x = minX; x < maxX; x++) {
_holder.X = x * TileWidth;
_holder.Y = y * TileHeight;
var t = tileLayer[y * Width + x];
spriteBatch.Draw(
t.Texture,
_holder,
t.SourceRectangle,
Color.White,
0,
Vector2.Zero,
t.SpriteEffects,
0);
}
}

Why does DrawString look so crappy?

I am trying to add a text scale to a color image.
The agcScale.jpg image (below) is 2 winform labels on the top and bottom and 2 winform pictureboxes on the left and right.
The exact same code was used to produce the strings in the right and left pictureboxes, the only difference is that pictureBoxAgcVscale contains only the strings.
Why does DrawString in pictureBoxAgc look fine but DrawString in pictureBoxAgcVscale look so bad? I can probably fix pictureBoxAgcVscale by doing a bmp.SetPixel for each pixel but that seems like the wrong way to fix this.
private void DisplayAgcVscale(double min, double max)
{
var bmp = new Bitmap(pictureBoxAgcVscale.Width, pictureBoxAgcVscale.Height);
var c = (max - min) / bmp.Height;
using (var g = Graphics.FromImage(bmp))
{
var font = new Font("Microsoft Sans Serif", 8.25F);
var y1 = bmp.Height / 10;
for (var y = y1; y < bmp.Height; y += y1)
{
var agc = y * c + min;
var text = agc.ToString("#0.000V");
var h = bmp.Height - y - font.Height / 2;
g.DrawString(text, font, Brushes.Black, 0, h);
}
}
pictureBoxAgcVscale.Image = bmp;
}
You are drawing black text on a transparent background. The anti-aliasing pixels are fading from black to black, no choice, turning the letters into blobs. It works for the text on the left because you draw the pixels first.
You forgot g.Clear().
I had a similar issue, but in a listbox, and it wasn't resolved by clearing the rectangle. I had to apply a "TextRenderingHint":
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
e.Graphics.DrawString(listText, myFont, myBrush, e.Bounds, StringFormat.GenericDefault);

Categories

Resources