Draw rectangle C# Mouse_down working Mouse_up not - c#

I want to draw an rectangle on an form the mouse_down event is working fine, but how do i programm the mouse_up. Should how do i dertermine the starting coordinates.
http://oi49.tinypic.com/2wcnof8.jpg
Rectangle rect = new Rectangle();
Color rastercolor = Color.Black;
private void drawGrid(Color rastercolor)
{
Graphics gfx = this.CreateGraphics();
Pen pen = new Pen(rastercolor);
for (int i = 0; i <= 2000; i = i + 20)
{
gfx.DrawLine(pen, 0, i, 2000, i);
}
for (int x = 0; x < 2000; x = x + 20)
{
gfx.DrawLine(pen, x, 0, x, 2000);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
rect = new Rectangle(e.X, e.Y, 0, 0);
if (e.Button == MouseButtons.Middle)
{
ColorDialog coldial = new ColorDialog();
coldial.ShowDialog();
Color rastercolor = coldial.Color;
tekenGrid(rastercolor);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
}
}
protected override void OnPaint(PaintEventArgs e)
{
tekenGrid(rastercolor);
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
private void Frm1_MouseUp(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Red, 2);
g.DrawRectangle(pen, rect);
}
private void Frm1_Load(object sender, EventArgs e)
{
}
private void Frm1_MouseDown(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Blue, 2);
g.DrawRectangle(pen, rect);
}
}
}
Any help would be greatly appreciated,

Not sure if this is what you are upto. Please try this code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle rect = new Rectangle();
Color _rastercolor = Color.Black;
private Pen _pen=new Pen(Color.Red,2);
private void tekenGrid(Color rastercolor, Graphics gfx)
{
Pen pen = new Pen(rastercolor);
for (int i = 0; i <= 2000; i = i + 20)
{
gfx.DrawLine(pen, 0, i, 2000, i);
}
for (int x = 0; x < 2000; x = x + 20)
{
gfx.DrawLine(pen, x, 0, x, 2000);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
rect = new Rectangle(e.X, e.Y, 0, 0);
if (e.Button == MouseButtons.Middle)
{
ColorDialog coldial = new ColorDialog();
coldial.ShowDialog();
Color rastercolor = coldial.Color;
tekenGrid(rastercolor,this.CreateGraphics());
}
else
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
this.Refresh();
}
base.OnMouseMove(e);
}
protected override void OnPaint(PaintEventArgs e)
{
tekenGrid(_rastercolor,e.Graphics);
e.Graphics.DrawRectangle(_pen, rect);
}
private void Frm1_MouseUp(object sender, MouseEventArgs e)
{
_pen = new Pen(Color.Red, 2);
this.Refresh();
}
private void Frm1_Load(object sender, EventArgs e)
{
}
private void Frm1_MouseDown(object sender, MouseEventArgs e)
{
_pen = new Pen(Color.Blue, 2);
}
}

Related

Save in a Jpg file a part of a Picturebox Image

I use the code provided by Erno with some modification like using DrawRect instead of FillRect to draw the selected area.
You can see the sample code in this thread :
How to select an area on a PictureBox.Image with mouse in C#
private Point RectStartPoint;
private Rectangle Rect = new Rectangle();
private Pen pen = new Pen(Color.Black, 2);
private void VisuelArchive_Load(object sender, EventArgs e)
{
pictureBox1.ImageLocation = fichierArchive;
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
}
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
Point tempEndPoint = e.Location;
Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X), Math.Min(RectStartPoint.Y, tempEndPoint.Y));
Rect.Size = new Size(Math.Abs(RectStartPoint.X - tempEndPoint.X), Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
pictureBox1.Invalidate();
}
private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
// Determine the initial rectangle coordinates...
RectStartPoint = e.Location;
Invalidate();
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
// Draw the rectangle...
if (pictureBox1.Image != null)
{
if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
{
e.Graphics.DrawRectangle(pen, Rect);
}
}
}
However I have some problem saving the selected area in a Jpg. I use this code but it seems that the Rect references are not good for that, i save a nearby area not the exact location.
Someone have an idea about how to save the exact location on the PictureBox Image ?
private void ButtonExport_Click(object sender, EventArgs e)
{
//exporter la sélection
Bitmap bmp = new Bitmap(Rect.Size.Width,Rect.Size.Height);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.DrawImage(pictureBox1.Image, new Rectangle(0, 0, Rect.Size.Width, Rect.Size.Height), Rect, GraphicsUnit.Pixel);
}
bmp.Save(Directory.GetCurrentDirectory() + "\\Archives\\" + numFiche.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

drawing flickers

have made something to draw on the screen(as overlay for everyting else) but when I move something over the drawing it starts flickering, I have already set DoubleBuffered on true
is their a way to fix this with a dll,function,rendering?
private void button2_Click(object sender, EventArgs e)
{
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Point midx = new Point(960, 960);
Point midy = new Point(540, 540);
Point LinksBoven = new Point(10, 10);
Point pt = Cursor.Position;
string letter = "drawing on";
float emSize = 12;
while (true)
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(0, 200, 0));
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
if (cbCircel.Checked == true)
{
g.DrawEllipse(Pens.Black, midx.X - 10, midy.Y - 10, 20, 20);
}
if (cbKruis.Checked == true)
{
g.DrawLine(myPen, 940, 540, 980, 540);
g.DrawLine(myPen, 960, 560, 960, 520);
}
pt.X = 10;
pt.Y = 10;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular), new SolidBrush(Color.Green), pt);
}
}
}

Print Image in Picturebox and the Highlighted Areas

I'm using WinForms. In my form i have a picturebox that contains an image. I provided my code which highlights images by right-clicking and dragging the mouse.
How do I print the image and what i highlighted in the picturebox?
private Random _rnd = new Random();
private Point _pt;
private Point _pt2;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
//set the upper left point of our selection rectangle
if (e.Button == MouseButtons.Left)
_pt = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//display the selected part when mouse button gets released
if (e.Button == MouseButtons.Left)
{
GenerateBmp();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
//if we have a valid rectangle, draw it
if (_pt.X - _pt2.X != 0 && _pt.Y - _pt2.Y != 0)
{
//fill
using (SolidBrush sb = new SolidBrush(Color.FromArgb(95, 255, 255, 0)))
e.Graphics.FillRectangle(sb, new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y));
//draw
e.Graphics.DrawRectangle(Pens.Blue, new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y));
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//set the bottom right one
if (e.Button == MouseButtons.Left)
{
_pt2 = e.Location;
this.pictureBox1.Invalidate();
}
}
private void GenerateBmp()
{
//check, if we have a valid rectangle
if (_pt2.X - _pt.X > 0 && _pt2.Y - _pt.Y > 0)
{
//create that rectangle
Rectangle r = new Rectangle(_pt.X, _pt.Y, _pt2.X - _pt.X, _pt2.Y - _pt.Y);
//create a new Bitmap with the size of the selection-rectangle
Bitmap bmp = new Bitmap(r.Width, r.Height);
//draw the selectex part of the original image
using (Graphics g = Graphics.FromImage(bmp))
g.DrawImage(this.pictureBox1.Image, new Rectangle(0, 0, r.Width, r.Height), r, GraphicsUnit.Pixel);
}
}
private Bitmap SetUpPictures(PictureBox pb)
{
//create a bitmap to display
Bitmap bmp1 = new Bitmap(pb.ClientSize.Width, pb.ClientSize.Height);
//get the graphics-context
using (Graphics g = Graphics.FromImage(bmp1))
{
//get a random, opaque, color
Color c = Color.FromArgb(255, _rnd.Next(256), _rnd.Next(256), _rnd.Next(256));
g.Clear(c);
//better smoothinmode for round shapes
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//draw ten shapes to the bitmap
for (int i = 0; i < 10; i++)
{
//loaction and size rectangle
Rectangle r = new Rectangle(_rnd.Next(pb.ClientSize.Width / 2), _rnd.Next(pb.ClientSize.Height / 2),
_rnd.Next(pb.ClientSize.Width / 2), _rnd.Next(pb.ClientSize.Height / 2));
//random color
Color c2 = Color.FromArgb(_rnd.Next(256), _rnd.Next(256), _rnd.Next(256), _rnd.Next(256));
//one color brush
using (SolidBrush sb = new SolidBrush(c2))
{
//check, if i is odd or even and decide on that to draw rectangles or ellipses
if ((i & 0x01) == 1)
g.FillEllipse(sb, r);
else
g.FillRectangle(sb, r);
}
}
}
//return our artwork
return bmp1;
}
private void Btn_Print_Click(object sender, EventArgs e)
{
System.Drawing.Printing.PrintDocument myPrintDocument1 = new System.Drawing.Printing.PrintDocument();
PrintDialog myPrinDialog1 = new PrintDialog();
myPrintDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(DVPrintDocument_PrintPage);
myPrinDialog1.Document = myPrintDocument1;
if (myPrinDialog1.ShowDialog() == DialogResult.OK)
{
myPrintDocument1.Print();
}
}
private void DVPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(pictureBox1.Image, 25, 25, 800, 1050);
var rc = new RectangleF(0, 0, pictureBox1.Image.Width / 100f, pictureBox1.Image.Height / 100f);
e.Graphics.DrawImage(pictureBox1.Image, rc);
}
You can draw the content of picturebox simply using DrawToBitmap method:
For example:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, new Rectangle(10, 10, 100, 100));
}
private void button1_Click(object sender, EventArgs e)
{
this.printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
var bmp=new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
this.pictureBox1.DrawToBitmap(bmp,this.pictureBox1.ClientRectangle);
e.Graphics.DrawImageUnscaled(bmp, 0, 0);
}
And here is the printed result:

Centroid tracking issue on Aforge C#

I am creating a program that can track multiple objects and get their centroid eventually I would use these centroids to connect to the nearest centroid of another object. But my problem is, my program tracks only one significant object on the video and it doesn't seem to display the centroid of this object. anyone can help me?
namespace Video_Processing_fixed_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap video;
Graphics g;
bool OnOff;
int mode;
int thoigiandemnguoc = 5;
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame+=new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
video = (Bitmap)eventArgs.Frame.Clone();
Bitmap video2 = (Bitmap)eventArgs.Frame.Clone();
g = Graphics.FromImage(video2);
g.DrawString("Test", new Font("Arial", 20), new SolidBrush(Color.White), new PointF(2, 2));
g.Dispose();
if (mode == 1)
{
// create filter
EuclideanColorFiltering filter = new EuclideanColorFiltering();
// set center colol and radius
filter.CenterColor = Color.FromArgb(215, 30, 30);
filter.Radius = 100;
// apply the filter
filter.ApplyInPlace(video2);
BlobCounter blobcounter = new BlobCounter();
blobcounter.MinWidth = 5;
blobcounter.MinHeight = 5;
blobcounter.FilterBlobs = true;
blobcounter.ObjectsOrder = ObjectsOrder.Area;
blobcounter.ProcessImage(video2);
Blob[] blobs = blobcounter.GetObjectsInformation();
AForge.Point Center = new AForge.Point();
if (blobs.Length > 0)
{
Center.X = blobs.Average(c => c.CenterOfGravity.X);
Center.Y = blobs.Average(c => c.CenterOfGravity.Y);
}
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach(Rectangle recs in rects)
if (rects.Length > 0)
{
foreach (Rectangle objectRect in rects)
{
Graphics graphic = Graphics.FromImage(video2);
using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
{
graphic.DrawRectangle(pen, objectRect);
}
graphic.Dispose();
}
}
( Pen pen = new Pen(Color.White,3))
pictureBox2.Image = video2;
pictureBox1.Image = video;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning==true)
{
FinalFrame.SignalToStop();
FinalFrame.WaitForStop();
}
}
private void button2_Click(object sender, EventArgs e)
{
pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
}
private void ButObjTrack_Click(object sender, EventArgs e)
{
mode = 1;
}
private void StopButt_Click(object sender, EventArgs e)
{
FinalFrame.SignalToStop();
}
}
}
You do not display the average center value. Change these lines:
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach(Rectangle recs in rects)
if (rects.Length > 0)
{
foreach (Rectangle objectRect in rects)
{
Graphics graphic = Graphics.FromImage(video2);
using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
{
graphic.DrawRectangle(pen, objectRect);
}
graphic.Dispose();
}
}
To these:
Rectangle[] rects = blobcounter.GetObjectsRectangles();
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Graphics graphic = Graphics.FromImage(video2);
foreach (Rectangle objectRect in rects)
{
graphic.DrawRectangle(Pens.LightGreen, objectRect);
}
graphic.DrawRectangle(Pens.Red, Center.X - 4, Center.Y - 4, 8, 8);
graphic.Dispose();
}
}

C# Save modified image in panel

I am attempting to save an image as modified by graphics tools such as pens and shapes that can be drawn onto the image. I have done this using a panel with background image and trying to set up a bit map that will save changes within this panel:
private void saveToolStripButton_Click(object sender, EventArgs e)
{
//sets panel1 contents as bit map to be saved at set locations
int width = panel1.Size.Width;
int height = panel1.Size.Height;
using (Bitmap bmp = new Bitmap(width, height))
{
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, width, height));
bmp.Save(#"C:\Users\Me\Pics\testBitmap.jpeg", ImageFormat.Jpeg);
}
MessageBox.Show("Your image has been saved");
}
Once the save button is clicked, the image saves ok but the changes made with the graphics tools do not show up. Can anyone suggest a solution?
Here is some code regarding the graphics tool i've set up for use within the panel:
{
InitializeComponent();
//Create graphics object in panel1
g = panel1.CreateGraphics();
}
private void btnExit2_Click(object sender, EventArgs e)
{
this.Close();
}
Graphics g;
//set a drawing boolean
bool draw = false;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
draw = true;
if (drawSq)
{
SolidBrush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
if (toolStripTextBox1.Text != "")
{
g.FillRectangle(brush, e.X, e.Y, Convert.ToInt32(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox1.Text));
}
else if (toolStripTextBox1.Text == "")
{
MessageBox.Show("Please enter a shape size");
}
draw = false;
drawSq = false;
}
}
and more:
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
mouseX = null;
mouseY = null;
}
//null values allow freehand style drawing
int? mouseX = null;
int? mouseY = null;
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
//creates a pen tool and sets properties by mouse location
if (draw)
{
Pen pen = new Pen(btnColor.ForeColor, float.Parse(txtBox1.Text));
g.DrawLine(pen, new Point(mouseX ?? e.X, mouseY ?? e.Y), new Point(e.X, e.Y));
mouseX = e.X;
mouseY = e.Y;
}
}
Let's try to fix this.
Start by creating your image first:
Bitmap bmp;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
}
Now when you want to draw on it:
void panel1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
using (Graphics g = Graphics.FromImage(bmp)) {
g.FillEllipse(Brushes.Red, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
}
panel1.Invalidate();
}
}
And display the results:
void panel1_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawImage(bmp, Point.Empty);
}
To save, just use your bitmap:
bmp.Save(#"c:\filename.png", ImageFormat.Png);
Use Double buffering with Panel to avoid the flickering.
This will works fine. I tested it and worked well........
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace drawing
{
public partial class Form2 : Form
{
Graphics g;
bool startPaint = false;
int? initX = null;
int? initY = null;
bool drawSquare = false;
bool drawRectangle = false;
bool drawCircle = false;
public Form2()
{
InitializeComponent();
bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
}
Bitmap bmp;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (startPaint)
{
using ( g = Graphics.FromImage(bmp))
{
// g.FillEllipse(Brushes.Black, new Rectangle(e.X, e.Y , 5, 5));
Pen p = new Pen(btn_PenColor.BackColor, float.Parse(cmb_PenSize.Text));
g.DrawLine(p, new Point(initX ?? e.X, initY ?? e.Y), new Point(e.X, e.Y));
initX = e.X;
initY = e.Y;
//g.DrawImage(bmp, new Rectangle(e.X - 4, e.Y - 4, 8, 8));
}
panel1.Invalidate();
}
}
private void pnl_Draw_MouseDown(object sender, MouseEventArgs e)
{
startPaint = true;
if (drawSquare)
{
//Use Solid Brush for filling the graphic shapes
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
//setting the width and height same for creating square.
//Getting the width and Heigt value from Textbox(txt_ShapeSize)
g.FillRectangle(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
//setting startPaint and drawSquare value to false for creating one graphic on one click.
startPaint = false;
drawSquare = false;
}
if (drawRectangle)
{
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
//setting the width twice of the height
g.FillRectangle(sb, e.X, e.Y, 2 * int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
startPaint = false;
drawRectangle = false;
}
if (drawCircle)
{
SolidBrush sb = new SolidBrush(btn_PenColor.BackColor);
g.FillEllipse(sb, e.X, e.Y, int.Parse(txt_ShapeSize.Text), int.Parse(txt_ShapeSize.Text));
startPaint = false;
drawCircle = false;
}
}
private void pnl_Draw_MouseUp(object sender, MouseEventArgs e)
{
startPaint = false;
initX = null;
initY = null;
}
void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(bmp, Point.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
bmp.Save("D://filename.jpg", ImageFormat.Png);
}
}
}

Categories

Resources