Draw selection Area in WinForm Application - c#

In my WinForm I need to draw selection area on the screen. User should be able to drag selected rectangle on corners or border to resize. As below:
I could draw the rectangle with solid brush.
How can I make it resizeable when dragging from border or corner?
private void panel1_MouseDown(object sender, MouseEventArgs e) {
using (Graphics g = this.panel1.CreateGraphics()) {
Pen pen = new Pen(Color.Black, 2);
Brush brush = new SolidBrush(this.panel1.BackColor);
g.FillRectangle(brush, this.panel1.Bounds);
g.DrawRectangle(pen, e.X, e.Y, 20, 20);
pen.Dispose();
brush.Dispose();
}
}

Instead of using MouseDown, I think you can use MouseMove.
At first, this event checks if left button is pressed:
if(e.Button == MouseButtons.Left)) {
//Check for the position of your mouse
}
Now you will put some ifstatement to be sure you will redraw your rectangle depending on your little resize boxes. Every if will recalculate the rectangle, erasing the old one and plotting the newest.
Hope this helps.

Related

Drawing rectangle is overwriting existing bitmap c#

I have a grid already drawn to a picturebox and I wish to draw a rectangle in the cell the mouse is clicked in. I'm trying to do this by drawing a rectangle in the top left corner of the cell and having it fill the entire cell.
However when I click the grid disappears.
How do I make it so the grid stays?
and is there an obvious better method for doing this?
The only way to redraw the grid is by pressing the button again but I want it to stay there.
Thanks.
You need to create a Graphics
Image bm;// Or Bitmap
using (var graphics = Graphics.FromImage(bm))
{
Draw(rects, graphics);
}
private static void Draw(List<Rectangle> rectangles, Graphics graphics)
{
Pen redPen = new Pen(Color.Red, 1);
foreach (var rect in rectangles)
{
graphics.DrawRectangle(redPen, rect);
}
}
At every mouse click in the mouse_click event at first you dispose the image of the picture box and then again assign the bitmap to the picturebox image otherwise you might face out of memory exception if you click on the grid too many times
private void InitializePictureBoxImage(PictureBox pictureBox)
{
if(pictureBox.Image != null)
{
var image = pictureBox.Image; // cache it to dispose
pictureBox.Image = null; // don't dispose an used object
image.Dispose(); // and dispose of it
}
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
pictureBox.Image = bitmap; // assign bitmap to image
}
Then call the method in the mouse_click event which you used to draw the picture box when you press the Generate Grid button in your form. Afterwards use graphics inside the mouse_click event to colour the grid which you pressed taking the X-Y coordinate from MouseEventArgs.
Altogether I think it will be something like this
private void Mouse_ClickEvent(object sender, MouseEventArgs e)
{
InitializePictureBoxImage(pictureBox);
DrawThePictureBoxImage(pictureBox);
using (Graphics graphics = Graphics.FromImage(pictureBox.Image))
{
Color color = Color.Blue;
color = Color.FromArgb(150, color.R, color.G, color.B); // lower the opacity so the writing in the grid is visible
var brush = new SolidBrush(color);
// Calculate the starting X-Y coordinate and Width,Height of the grid to color
graphics.FillRectangle(brush, startX, startY,
width, height);
}

FillRectangle over Child Controls Inside a FlowLayoutPanel

I want to draw a rectangle on Mousedown for Mousearea Select on my panel:
private void flowLayoutPanel1_Paint_1(object sender, PaintEventArgs e)
{
if (mouseDown)
{
Brush brush = new SolidBrush(Color.DodgerBlue);
Graphics g = this.flowLayoutPanel1.CreateGraphics();
g.FillRectangle(brush, selection);
}
}
Selection here has the rect area on which Mouse has been dragged upon.
But if I put Form-Elements, like a Picturebox , on this panel,
my rectangle is behind this button.
But I want to render it in the front.
What can I do to solve this problem ?

How to get all the pixel values inside a rectangle in C#

I'm developing a program to get all the pixels inside a rectangle. There is an image control and the user can click on a part inside it. When the user clicks on a particular location, a rectangle is drawn. I would like to get all the pixels inside that rectangle. I'm getting to draw the rectangle now. But i'm not able to get all the pixel values. Please find the code snippet for drawing the rectangle below.
private void panel1_Paint(object sender, PaintEventArgs e)
{
foreach (var rectKey in rectangles.Keys)
{
using (var pen = new Pen(rectKey)) //Create the pen used to draw the rectangle (using statement makes sure the pen is disposed)
{
//Draws all rectangles for the current color
//Note that we're using the Graphics object that is passed into the event handler.
e.Graphics.DrawRectangles(pen, rectangles[rectKey].ToArray());
}
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Color c = System.Drawing.Color.GreenYellow ; //Gets a color for which to draw the rectangle
//Adds the rectangle using the color as the key for the dictionary
if (!rectangles.ContainsKey(c))
{
rectangles.Add(c, new List<Rectangle>());
}
rectangles[c].Add(new Rectangle(e.Location.X - 12, e.Location.Y - 12, 25, 25)); //Adds the rectangle to the collection
}
//Make the panel repaint itself.
panel1.Refresh();// Directs to panel1_Paint() event
rectangles.Clear();
}
You would have to work with the Bitmap not the graphics object in this case.
Bitmap has a method to get pixels at a position
Bitmap bmp = Bitmap.FromFile("");
// Get the color of a pixel within myBitmap.
Color pixelColor = bmp.GetPixel(50, 50);
To read all pixels within a rectangle you could use the bmp.LockBits method.

How to move a circle drawn by GDI in .NET Framework with the mouse?

I drew some circles on the Form1 using GDI+, and the center of the circle is a small red rectangle of Custom Control which is derived from User Control, the BackgroundImage property ofForm1's a bitmap which is also drawn by GDI+ with several colors.
What I want is that when I move the red rectangle(the center of circle) with a mouse, the circle will also move following the red rectangle. Using the MouseDown, MouseMove event I could move the red rectangle smoothly with the mouse.
My problem is how to move the circle corresponding to the red rectangle(the center of circle).
I enabled the double buffering to solve the flicker problem. CircleCenter is an object of Custom Control class(e.g. the red rectangle). GObject is a Grahpics object.
Here is some key codes:
public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.DoubleBuffer | //enables double-buffering
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint,
true);
}
Point CCenterPoint = new Point();
private int Diameter = 250;
private void CircleCenterMouseDown(object sender, MouseEventArgs e)
{
CCenterPoint = new Point(-e.X, -e.Y);
}
private void CircleCenterMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point MousePos = CircleCenter.MousePosition;
MousePos.Offset(CCenterPoint.X, CCenterPoint.Y);
CircleCenter.Location = CircleCenter.Parent.PointToClient(MousePos);
CircleCenter.BringToFront();
CirclePen.Color = Color.Black;
GObject.DrawEllipse(CirclePen, CircleCenter.Left- Diameter/2, CircleCenter.Top - Diameter/2, Diameter, Diameter);
this.Invalidate();
}
}
How to remove the black circle drawn by GDI+ produced in the MouseMove proceed?
I googled several websites and didn't get a satisfied answer. Hope you could give me some hints,Thx!
Well, As I understand from your question, You just need to draw a circle around the red rectangle, This is quite easy.
In the Paint event of the Form, Add the following (assuming that your red rectangle control has the name "CircleCenter" and your Form was named "Form1"):
private void Form1_Paint(object sender, PaintEventArgs e)
{
// get the Graphics object of the form.
Graphics g = e.Graphics;
// create a think red pen for the circle drawing
Pen redPen = new Pen(Brushes.Red, 4.0f);
// drawing the circle
PointF ctrlCenter = GetCenterOfControl(CircleCenter);
g.DrawEllipse(redPen,
ctrlCenter.X - (Diameter / 2),
ctrlCenter.Y - (Diameter / 2),
Diameter, Diameter);
}
//The following little method to calculate the center point
PointF GetCenterOfControl(Control ctrl)
{
return new PointF(ctrl.Left + (ctrl.Width / 2),
ctrl.Top + (ctrl.Height / 2));
}
Any way, I know it looks long for such a simple task like Circle drawing! here is the ugly one line version of the above code:
e.Graphics.DrawEllipse(new Pen(Brushes.Red, 4.0f), (centerCircle.Left + (centerCircle.Width / 2)) - (Diameter / 2), (centerCircle.Top + (centerCircle.Height / 2)) - (Diameter / 2), Diameter, Diameter);
You will need to always reset the entire GObject (erase the images you drawn on it) and then redraw them all again.
This can be done by simply drawing a rectangle with the color of the object from which you obtained the Graphics object (although you didn't mentioned it, I think GObject is a Graphics object, obtained of some win control?).
So something like:
Control control = CircleCenter.Parent; // Parent control where you get Graphics object from.
System.Drawing.SolidBrush sBrush = new System.Drawing.SolidBrush(control.BackColor); // Brush to be used with the same color like the one of the parent control.
GObject.FilledRectangle(sBrush, new Rectangle(0, 0, control.Width, control.Height); // Erase background.
GObject.DrawEllipse(CirclePen, CircleCenter.Left- Diameter/2, CircleCenter.Top - Diameter/2, Diameter, Diameter); // Do your stuff.
should hide the old drawings and re-draw the circle on the new location.

How to assign a click event handler to part of a drawn rectangle?

Imagine I use the .NET graphic classes to draw a rectangle.
How could I then assign an event so that if the user clicks a certain point, or a certain point range, something happens (a click event handler)?
I was reading CLR via C# and the event section, and I thought of this scenario from what I had read.
A code example of this would really improve my understanding of events in C#/.NET.
Thanks
You can assign Click event handler to control whose surface will be used to draw rectangle.
Here is a small example:
When you click on form inside of rectangle it will be drawn with red border when you click outside it will be drawn with black border.
public partial class Form1 : Form
{
private Rectangle rect;
private Pen pen = Pens.Black;
public Form1()
{
InitializeComponent();
rect = new Rectangle(10, 10, Width - 30, Height - 60);
Click += Form1_Click;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawRectangle(pen, rect);
}
void Form1_Click(object sender, EventArgs e)
{
Point cursorPos = this.PointToClient(Cursor.Position);
if (rect.Contains(cursorPos))
{
pen = Pens.Red;
}
else
{
pen = Pens.Black;
}
Invalidate();
}
}
PointToClient method translates cursor coordinates to control-relative coordinates. I.e. if you cursor is at (screenX, screenY) position on the screen it can be at (formX, formY) position relatively to form's top-left corner. We need to call it to bring cursor position into coordinate system used by our rectangle.
Invalidate method makes control to redraw itself. In our case it triggers OnPaint event handler to redraw rectangle with a new border color.

Categories