I have the below which draws a rectangle on mouse drag and also a grid drawing script which draws a 32x32 grid on the picture box what I'm trying to do is snap the rectangle to the grid then screen shot inside the rectangle.
I've got the screen shot bit and the drawing of the rectangle just not the snapping to grid bit working.
private bool _selecting;
private Rectangle _selection;
private void picCanvas_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_selecting = true;
_selection = new Rectangle(new Point(e.X, e.Y), new Size());
}
}
private void picCanvas_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (_selecting)
{
_selection.Width = e.X - _selection.X;
_selection.Height = e.Y - _selection.Y;
pictureBox1.Refresh();
}
}
public Image Crop(Image image, Rectangle selection)
{
Bitmap bmp = image as Bitmap;
// Check if it is a bitmap:
if (bmp == null)
throw new ArgumentException("No valid bitmap");
// Crop the image:
Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat);
// Release the resources:
image.Dispose();
return cropBmp;
}
private void picCanvas_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left &&
_selecting &&
_selection.Size != new Size())
{
// Create cropped image:
//Image img = Crop(pictureBox1.Image, _selection);
// Fit image to the picturebox:
//pictureBox1.Image = img;
_selecting = false;
}
else
_selecting = false;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (_selecting)
{
// Draw a rectangle displaying the current selection
Pen pen = Pens.GreenYellow;
e.Graphics.DrawRectangle(pen, _selection);
}
Graphics g = e.Graphics;
int numOfCells = amount;
Pen p = new Pen(Color.LightGray);
for (int y = 0; y < numOfCells; ++y)
{
g.DrawLine(p, 0, y * ysize, numOfCells * ysize, y * ysize);
}
for (int x = 0; x < numOfCells; ++x)
{
g.DrawLine(p, x * xsize, 0, x * xsize, numOfCells * xsize);
}
}
First I would declare a snapping method
private Point SnapToGrid(Point p)
{
double x = Math.Round((double)p.X / xsize) * xsize;
double y = Math.Round((double)p.Y / ysize) * ysize;
return new Point((int)x, (int)y);
}
Then you can initialize the selection like this in MouseDown:
_selection = new Rectangle(SnapToGrid(e.Location), new Size());
And you can adjust the width in MouseMove like this:
Point dest = SnapToGrid(e.Location);
_selection.Width = dest.X - _selection.X;
_selection.Height = dest.Y - _selection.Y;
Related
I made a program that lets you do a random selection then the selected area to save into a new image, but I got a problem it doesn't work how it's supposed to... I will post my code here so you can have a look:
private List<Point> Points = null;
private bool Selecting = false;
private Bitmap SelectedArea = null;
private void pictureBox5_MouseDown(object sender, MouseEventArgs e)
{
Points = new List<Point>();
Selecting = true;
}
private void pictureBox5_MouseMove(object sender, MouseEventArgs e)
{
if (!Selecting) return;
Points.Add(new Point(e.X, e.Y));
pictureBox5.Invalidate();
}
private void pictureBox5_MouseUp(object sender, MouseEventArgs e)
{
Selecting = false;
// Copy the selected area.
SelectedArea = GetSelectedArea(pictureBox5.Image, Color.Transparent, Points);
SelectedArea.Save(#"C:\Users\User\Desktop\Gallery\image" + NumberOfClick.ToString() + "cropped.jpeg", ImageFormat.Jpeg);
string filename = #"C:\Users\User\Desktop\Gallery\image" + NumberOfClick.ToString() + "cropped.jpeg";
if(File.Exists(filename))
{
button1.Visible = true;
pictureBox5.Visible = false;
}
}
private void pictureBox5_Paint(object sender, PaintEventArgs e)
{
if ((Points != null) && (Points.Count > 1))
{
using (Pen dashed_pen = new Pen(Color.Black))
{
dashed_pen.DashPattern = new float[] { 5, 5 };
e.Graphics.DrawLines(Pens.White, Points.ToArray());
e.Graphics.DrawLines(dashed_pen, Points.ToArray());
}
}
}
private Bitmap GetSelectedArea(Image source, Color bg_color, List<Point> points)
{
// Make a new bitmap that has the background
// color except in the selected area.
Bitmap big_bm = new Bitmap(source);
using (Graphics gr = Graphics.FromImage(big_bm))
{
// Set the background color.
gr.Clear(bg_color);
// Make a brush out of the original image.
using (Brush br = new TextureBrush(source))
{
// Fill the selected area with the brush.
gr.FillPolygon(br, points.ToArray());
// Find the bounds of the selected area.
Rectangle source_rect = GetPointListBounds(points);
// Make a bitmap that only holds the selected area.
Bitmap result = new Bitmap(
source_rect.Width, source_rect.Height);
// Copy the selected area to the result bitmap.
using (Graphics result_gr = Graphics.FromImage(result))
{
Rectangle dest_rect = new Rectangle(0, 0,
source_rect.Width, source_rect.Height);
result_gr.DrawImage(big_bm, dest_rect,
source_rect, GraphicsUnit.Pixel);
}
// Return the result.
return result;
}
}
}
private Rectangle GetPointListBounds(List<Point> points)
{
int xmin = points[0].X;
int xmax = xmin;
int ymin = points[0].Y;
int ymax = ymin;
for (int i = 1; i < points.Count; i++)
{
if (xmin > points[i].X) xmin = points[i].X;
if (xmax < points[i].X) xmax = points[i].X;
if (ymin > points[i].Y) ymin = points[i].Y;
if (ymax < points[i].Y) ymax = points[i].Y;
}
return new Rectangle(xmin, ymin, xmax - xmin, ymax - ymin);
}
This is how I am doing and saving the cropped images.
And also this is how I am uploading the pictures:
OpenFileDialog f = new OpenFileDialog();
f.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
if (f.ShowDialog() == DialogResult.OK)
{
currentImage = Image.FromFile(f.FileName);
pictureBox1.Image = currentImage;
}
pictureBox1.Image.Save(#"C:\Users\User\Desktop\Gallery\image1.jpeg", ImageFormat.Jpeg);
DialogResult result = MessageBox.Show("Crop your image", "Information", MessageBoxButtons.OK);
if(result == DialogResult.OK)
{
pictureBox5.Visible = true;
button1.Visible = false;
pictureBox5.Image = pictureBox1.Image;
}
In pictureBox5 I am selecting and cropping the picture.
mySelection
croppedImage
You need to calculate the zoom and the offset of the image when it is zoomed.
Here is how to do that; this assumes the PictureBox is indeed in Zoom mode, not in Stretch mode. If you stretch it you need to calculate the zooms for x and y separately..
SizeF sp = pictureBox5.ClientSize;
SizeF si = pictureBox5.Image.Size;
float rp = sp.Width / sp.Height; // calculate the ratios of
float ri = si.Width / si.Height; // pbox and image
float zoom = (rp > ri) ? sp.Height / si.Height : sp.Width / si.Width;
float offx = (rp > ri) ? (sp.Width - si.Width * zoom) / 2 : 0;
float offy = (rp <= ri)? (sp.Height - si.Height * zoom) / 2 : 0;
Point offset = Point.Round(new PointF(offx, offy));
You calculate this after setting the Image and after resizing the PictureBox..
Now you can transform each drawn point into a zoomed or an unzoomed coordinate:
PointF zoomed(Point p1, float zoom, Point offset)
{
return (new PointF(p1.X * zoom + offset.X, p1.Y * zoom + offset.Y));
}
PointF unZoomed(Point p1, float zoom, Point offset)
{
return (new PointF((p1.X - offset.X) / zoom, (p1.Y - offset.Y) / zoom));
}
Here is a demo the draws on to either a normal (left) or a zoomed in (middle) image. To the right is the result of placing your GetSelectedArea bitmap onto a PictureBox with a checkerbox background:
Case 1: If you store the points as they come in: In your GetSelectedArea method use this point list instead:
private Bitmap GetSelectedArea(Image source, Color bg_color, List<Point> points)
{
var unzoomedPoints =
points.Select(x => Point.Round((unZoomed(Point.Round(x), zoom, offset))))
.ToList();
// Make a new bitmap that has the background
After this replace each reference to points in the method by one to unzoomedPoints. Actually there are just two of them..
Case 2: If you store the points already 'unZoomed' :
Points.Add(unZoomed(e.Location, zoom, offset));
you can use the list directly..
How can I make a free-form selection (like in paint or photoshop) in a picture box and then crop that selection and save it to a folder?
I already did a rectangle crop but I want that free-form selection..
Here is my rectangle crop:
Image img;
bool mouseClicked;
Point startPoint = new Point();
Point endPoint = new Point();
Rectangle rectCropArea;
private void Button1_Click(System.Object sender, System.EventArgs e)
{
}
private void OnLoad(System.Object sender, System.EventArgs e)
{
loadPrimaryImage();
}
private void loadPrimaryImage()
{
img = Image.FromFile("..\\..\\images.jpg");
PictureBox1.Image = img;
}
private void PicBox_MouseUp(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
mouseClicked = false;
if ((endPoint.X != -1)) {
Point currentPoint = new Point(e.X, e.Y);
Y1.Text = e.X.ToString();
Y2.Text = e.Y.ToString();
}
endPoint.X = -1;
endPoint.Y = -1;
startPoint.X = -1;
startPoint.Y = -1;
}
private void PicBox_MouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
mouseClicked = true;
startPoint.X = e.X;
startPoint.Y = e.Y;
//Display coordinates
X1.Text = startPoint.X.ToString();
Y1.Text = startPoint.Y.ToString();
endPoint.X = -1;
endPoint.Y = -1;
rectCropArea = new Rectangle(new Point(e.X, e.Y), new Size());
}
private void PicBox_MouseMove(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
Point ptCurrent = new Point(e.X, e.Y);
if ((mouseClicked)) {
if ((endPoint.X != -1)) {
//Display Coordinates
X1.Text = startPoint.X.ToString();
Y1.Text = startPoint.Y.ToString();
X2.Text = e.X.ToString();
Y2.Text = e.Y.ToString();
}
endPoint = ptCurrent;
if ((e.X > startPoint.X & e.Y > startPoint.Y)) {
rectCropArea.Width = e.X - startPoint.X;
rectCropArea.Height = e.Y - startPoint.Y;
} else if ((e.X < startPoint.X & e.Y > startPoint.Y)) {
rectCropArea.Width = startPoint.X - e.X;
rectCropArea.Height = e.Y - startPoint.Y;
rectCropArea.X = e.X;
rectCropArea.Y = startPoint.Y;
} else if ((e.X > startPoint.X & e.Y < startPoint.Y)) {
rectCropArea.Width = e.X - startPoint.X;
rectCropArea.Height = startPoint.Y - e.Y;
rectCropArea.X = startPoint.X;
rectCropArea.Y = e.Y;
} else {
rectCropArea.Width = startPoint.X - e.X;
rectCropArea.Height = startPoint.Y - e.Y;
rectCropArea.X = e.X;
rectCropArea.Y = e.Y;
}
PictureBox1.Refresh();
}
}
private void PicBox_Paint(System.Object sender, System.Windows.Forms.PaintEventArgs e)
{
Pen drawLine = new Pen(Color.Red);
drawLine.DashStyle = DashStyle.Dash;
e.Graphics.DrawRectangle(drawLine, rectCropArea);
}
private void btnCrop_Click(System.Object sender, System.EventArgs e)
{
PictureBox2.Refresh();
Bitmap sourceBitmap = new Bitmap(PictureBox1.Image, PictureBox1.Width, PictureBox1.Height);
Graphics g = PictureBox2.CreateGraphics();
if (!(CheckBox1.Checked)) {
g.DrawImage(sourceBitmap, new Rectangle(0, 0, PictureBox2.Width, PictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
} else {
int x1 = 0;
int x2 = 0;
int y1 = 0;
int y2 = 0;
try {
x1 = Convert.ToInt32(CX1.Text);
x2 = Convert.ToInt32(CX2.Text);
y1 = Convert.ToInt32(CY1.Text);
y2 = Convert.ToInt32(CY2.Text);
} catch (Exception ex) {
MessageBox.Show("Enter valid Coordinates (only Integer values)");
}
if (((x1 < x2 & y1 < y2))) {
rectCropArea = new Rectangle(x1, y1, x2 - x1, y2 - y1);
} else if ((x2 < x1 & y2 > y1)) {
rectCropArea = new Rectangle(x2, y1, x1 - x2, y2 - y1);
} else if ((x2 > x1 & y2 < y1)) {
rectCropArea = new Rectangle(x1, y2, x2 - x1, y1 - y2);
} else {
rectCropArea = new Rectangle(x2, y2, x1 - x2, y1 - y2);
}
PictureBox1.Refresh();
//This repositions the dashed box to new location as per coordinates entered.
g.DrawImage(sourceBitmap, new Rectangle(0, 0, PictureBox2.Width, PictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
}
}
private void pictureBox1_MouseClick(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
PictureBox1.Refresh();
}
private void CheckBox1_CheckedChanged(System.Object sender, System.EventArgs e)
{
if ((CheckBox1.Checked)) {
CX1.Visible = true;
Label10.Visible = true;
CY1.Visible = true;
Label9.Visible = true;
CX2.Visible = true;
Label8.Visible = true;
CY2.Visible = true;
Label7.Visible = true;
X1.Text = "0";
X2.Text = "0";
Y1.Text = "0";
Y2.Text = "0";
} else {
CX1.Visible = false;
Label10.Visible = false;
CY1.Visible = false;
Label9.Visible = false;
CX2.Visible = false;
Label8.Visible = false;
CY2.Visible = false;
Label7.Visible = false;
}
}
public Form1()
{
Load += OnLoad;
}
}
To copy a free-form selection you need to work with polygons.
Here is a complete example. Just paste this into a new solution and try it out (just change the path to the images).
It will create 2 pictureboxes and load an image into the first one and also create an image. Then you can click on the first image and when you have clicked 2 times it will start to show a selection, when you are finished just press the button and it will copy the selection to the other pictureBox and then save it as an png image.
What it does is to create a brush from the first image and then paint the polygon onto another image and set the other pixels in the rectangle to a background color of your choice, in this case the color: Color.Transparent.
Example:
public partial class Form1 : Form {
private List<Point> _points = new List<Point>();
private PictureBox _pictureBox1;
private PictureBox _pictureBox2;
private Button _button1;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
Size = new Size(1366, 675);
_pictureBox1 = new PictureBox {
Location = new Point(12, 51),
Size = new Size(651, 474),
BorderStyle = BorderStyle.FixedSingle
};
_pictureBox2 = new PictureBox
{
Location = new Point(669, 51),
Size = new Size(651, 474),
BorderStyle = BorderStyle.FixedSingle
};
_button1 = new Button {
Text = #"Copy selected area",
Location = new Point(13, 13),
Size = new Size(175, 23)
};
Controls.AddRange(new Control[] { _pictureBox1, _pictureBox2, _button1 });
_pictureBox1.Image = Image.FromFile(#"d:\temp\Hopetoun_falls.jpg");
_points = new List<Point>();
_pictureBox1.MouseDown += delegate(object o, MouseEventArgs args) { _points.Add(args.Location); _pictureBox1.Refresh(); };
_pictureBox1.Paint += pictureBox1_Paint;
_button1.Click += button_Click;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
if (_points.Count < 2) {
return;
}
var max = _points.Count;
for (int i = 1; i < max; i++) {
e.Graphics.DrawLine(Pens.Red, _points[i-1].X, _points[i-1].Y, _points[i].X, _points[i].Y);
}
e.Graphics.DrawLine(Pens.Red, _points[max - 1].X, _points[max - 1].Y, _points[0].X, _points[0].Y);
}
private static Bitmap GetSelectedArea(Image source, Color bgColor, List<Point> points) {
var bigBm = new Bitmap(source);
using (var gr = Graphics.FromImage(bigBm)) {
// Set the background color.
gr.Clear(bgColor);
// Make a brush out of the original image.
using (var br = new TextureBrush(source)) {
// Fill the selected area with the brush.
gr.FillPolygon(br, points.ToArray());
// Find the bounds of the selected area.
var sourceRect = GetPointListBounds(points);
// Make a bitmap that only holds the selected area.
var result = new Bitmap(sourceRect.Width, sourceRect.Height);
// Copy the selected area to the result bitmap.
using (var resultGr = Graphics.FromImage(result)) {
var destRect = new Rectangle(0, 0, sourceRect.Width, sourceRect.Height);
resultGr.DrawImage(bigBm, destRect, sourceRect, GraphicsUnit.Pixel);
}
// Return the result.
return result;
}
}
}
private static Rectangle GetPointListBounds(List<Point> points) {
int xmin = points[0].X;
int xmax = xmin;
int ymin = points[0].Y;
int ymax = ymin;
for (int i = 1; i < points.Count; i++) {
if (xmin > points[i].X) xmin = points[i].X;
if (xmax < points[i].X) xmax = points[i].X;
if (ymin > points[i].Y) ymin = points[i].Y;
if (ymax < points[i].Y) ymax = points[i].Y;
}
return new Rectangle(xmin, ymin, xmax - xmin, ymax - ymin);
}
private void button_Click(object sender, EventArgs e) {
if (_points.Count < 3) {
return;
}
var img = GetSelectedArea(_pictureBox1.Image, Color.Transparent, _points);
_pictureBox2.Image = img;
_pictureBox2.Image.Save(#"d:\temp\sample.png", ImageFormat.Png);
}
}
I have a picturebox that I want the user of my winform to be able to interact with by zooming and dragging the image. Right now that form looks like this
I have the drag and zoom methods implemented. Those look like this.
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
// If the mouse wheel is moved forward (Zoom in)
if (e.Delta > 0)
{
// Change the size of the picturebox, multiply it by the ZOOMFACTOR
pictureBox1.Width = (int)(pictureBox1.Width * 1.25);
pictureBox1.Height = (int)(pictureBox1.Height * 1.25);
// Formula to move the picturebox, to zoom in the point selected by the mouse cursor
pictureBox1.Top = (int)(e.Y - 1.25 * (e.Y - pictureBox1.Top));
pictureBox1.Left = (int)(e.X - 1.25 * (e.X - pictureBox1.Left));
}
else
{
pictureBox1.Width = (int)(pictureBox1.Width / 1.25);
pictureBox1.Height = (int)(pictureBox1.Height / 1.25);
// Formula to move the picturebox, to zoom in the point selected by the mouse cursor
pictureBox1.Top = (int)(e.Y - 0.80 * (e.Y - pictureBox1.Top));
pictureBox1.Left = (int)(e.X - 0.80 * (e.X - pictureBox1.Left));
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
Console.WriteLine("Dragging: false");
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
dragging = true;
xDrag = e.X;
yDrag = e.Y;
Console.WriteLine("Dragging: true");
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Control c = sender as Control;
if (dragging && c != null)
{
c.Top = e.Y + c.Top - yDrag;
c.Left = e.X + c.Left - xDrag;
Console.WriteLine(e.Location.ToString());
}
}
The dragging works fine but the zooming does not work as expected. Instead of zooming in it pushes the image up and to the left as I "zoom in"
Out of curiousity I loaded a bitmap I saved off Google in to test the zoom and it works fine with bitmap images from files; it just doesn't work with images drawn with the Graphics object and I have no idea why. Any help would be greatly appreciated.
Paint event code for picturebox
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
RunEntry entry = this.passedHistory.SelectedItem as RunEntry;
if (entry == null)
{
return;
}
else if(entry.FileRead != null && checkBox1.Checked) //If ANS is selected and show all, get TRE
{
foreach(RunEntry r in passedHistory.Items)
{
if (r.TreComponentRead != null)
{
string ansName = Path.GetFileNameWithoutExtension(entry.FileName);
string treName = Path.GetFileNameWithoutExtension(r.FileName);
if(ansName.Equals(treName, StringComparison.OrdinalIgnoreCase))
{
entry.TreComponentRead = r.TreComponentRead;
}
}
}
}
if (isDraw && entry.FileRead != null)
{
//Preparing to draw
Graphics g = e.Graphics;
g.ScaleTransform(2f, 2f);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.Bicubic;
AnsFile objToDraw = entry.FileRead;
Pen pen = new Pen(Color.Black);
//Getting size of bitmap
int maxWidth = 0, maxHeight = 0;
foreach (AnsJoint joint in objToDraw.AnsJoints)
{
if (joint.Location.X.Length > maxWidth)
{
maxWidth = (int)joint.Location.X.Length;
}
if (joint.Location.Y.Length > maxHeight)
{
maxHeight = (int)joint.Location.Y.Length;
}
}
//Drawing joints //TODO: (Trello: Improve math behind visualizer)
foreach (AnsJoint joint in objToDraw.AnsJoints)
{
PointF jointPoint = this.ToCartesian(new PointF((float)joint.Location.X.Length - 4f, (float)joint.Location.Y.Length + 10f), maxHeight);
e.Graphics.DrawString(joint.JointID.ToString(), new Font(FontFamily.GenericMonospace, 6f, FontStyle.Regular, GraphicsUnit.Point, 1, false), Brushes.Black, jointPoint);
}
//Draw the panels and links //TODO: (Trello: Improve math behind visualizer)
foreach (AnsMember member in objToDraw.AnsMembers)
{
List<AnsPanel> panels = member.Panels; //Drawing the panels
foreach (AnsPanel pan in panels)
{
pen.Color = Color.Red;
PointF p1 = this.ToCartesian(new PointF((float)pan.I.Location.X.Length, (float)pan.I.Location.Y.Length), maxHeight);
PointF p2 = this.ToCartesian(new PointF((float)pan.J.Location.X.Length, (float)pan.J.Location.Y.Length), maxHeight);
g.DrawEllipse(pen, p1.X - 2.5f, p1.Y - 2.5f, 5, 5);
g.DrawEllipse(pen, p2.X - 2.5f, p2.Y - 2.5f, 5, 5);
g.DrawEllipse(pen, p1.X - 3, p1.Y - 3.3f, 5, 5);
g.DrawEllipse(pen, p2.X - 3, p2.Y - 3.3f, 5, 5);
pen.Color = Color.Black;
g.DrawLine(pen, p1, p2);
}
List<AnsLink> links = member.Links; //Drawing the links
foreach (AnsLink link in links)
{
PointF p1 = this.ToCartesian(new PointF((float)link.I.Location.X.Length, (float)link.I.Location.Y.Length), maxHeight);
PointF p2 = this.ToCartesian(new PointF((float)link.J.Location.X.Length, (float)link.J.Location.Y.Length), maxHeight);
g.FillEllipse(Brushes.Green, p1.X - 1.5f, p1.Y - 1.5f, 3, 3);
g.FillEllipse(Brushes.Green, p2.X - 1.5f, p2.Y - 1.5f, 3, 3);
g.DrawLine(pen, p1, p2);
}
}
pictureBox1.Tag = entry.FileName;
}
if (isDraw && entry.TreComponentRead != null)
{
//Preparing to draw
Graphics g = e.Graphics;
g.ScaleTransform(2f, 2f);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.Bicubic;
TreComponent objToDraw = entry.TreComponentRead;
Pen pen = new Pen(Color.Black);
int maxWidth = 0, maxHeight = 0;
foreach (Member member in objToDraw.Members)
{
foreach (GeometryClassLibrary.Point p in member.Geometry.Vertices)
{
if (p.X.Inches > maxWidth)
{
maxWidth = (int)p.X.Inches;
}
if (p.Y.Inches > maxHeight)
{
maxHeight = (int)p.Y.Inches;
}
}
}
maxHeight += 5; maxWidth += 5;
maxHeight += 15; maxWidth += 5;
foreach (Member member in objToDraw.Members)
{
List<PointF> pointsToDraw = new List<PointF>();
foreach (GeometryClassLibrary.Point p in member.Geometry.Vertices)
{
pointsToDraw.Add(ToCartesian(new PointF((float)p.X.Inches, (float)p.Y.Inches), maxHeight));
PointF pointToDraw = this.ToCartesian(new PointF((float)p.X.Inches, (float)p.Y.Inches), maxHeight);
g.FillEllipse(Brushes.Red, pointToDraw.X - 1.5f, pointToDraw.Y - 1.5f, 3, 3);
pointsToDraw.Add(pointToDraw);
}
g.DrawPolygon(pen, pointsToDraw.ToArray());
//Getting center of member and labeling member
float totalX = 0, totalY = 0;
foreach (PointF p in pointsToDraw)
{
totalX += p.X;
totalY += p.Y;
}
float centerX = totalX / pointsToDraw.Count;
float centerY = totalY / pointsToDraw.Count - 10;
PointF midPoint = new PointF(centerX, centerY);
g.DrawString(member.Name, new Font(FontFamily.GenericMonospace, 6f, FontStyle.Regular, GraphicsUnit.Point, 1, false), Brushes.Black, midPoint);
}
pictureBox1.Tag = entry.FileName;
}
}
I have been trying to write a program, to be able to load an image on a form and select a rectangle on it, then load that rectangle onto another picture box (pictureBox2), and I also want to be able to highlight what I have selected on the original picture, in pictureBox1, as I move my mouse.
So far I have this code, but it doesn't properly respond to the mouseMove event, the rectangle that I highlight isn't selected properly. What is the problem?
public partial class Form1 : Form
{
Bitmap original;
bool isSelecting;
int x0, y0, x1, y1;
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += new MouseEventHandler(picOriginal_MouseDown);
pictureBox1.MouseMove += new MouseEventHandler(picOriginal_MouseMove);
pictureBox1.MouseUp += new MouseEventHandler(picOriginal_MouseUp);
}
#region helpder methods
// Start selecting the rectangle.
private void picOriginal_MouseDown(object sender, MouseEventArgs e)
{
if(original != null)
{
isSelecting = true;
// Save the start point.
x0 = e.X;
y0 = e.Y;
}
}
// Continue selecting.
private void picOriginal_MouseMove(object sender, MouseEventArgs e)
{
if(original != null)
{
// Do nothing it we're not selecting an area.
if(!isSelecting) return;
// Save the new point.
x1 = e.X;
y1 = e.Y;
// Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(original);
// Draw the rectangle.
using(Graphics gr = Graphics.FromImage(bm))
{
gr.DrawRectangle(Pens.Red,
Math.Min(x0, x1), Math.Min(y0, y1),
Math.Abs(x0 - x1), Math.Abs(y0 - y1)
);
}
// Display the temporary bitmap.
pictureBox1.Image = new Bitmap(bm, new Size(pictureBox1.Width, pictureBox1.Height));
}
}
// Finish selecting the area.
private void picOriginal_MouseUp(object sender, MouseEventArgs e)
{
if(original != null)
{
// Do nothing it we're not selecting an area.
if(!isSelecting) return;
isSelecting = false;
// Display the original image.
pictureBox1.Image = original;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using(Graphics gr = Graphics.FromImage(area))
{
Rectangle source_rectangle =
new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1),
wid, hgt);
Rectangle dest_rectangle =
new Rectangle(0, 0, wid, hgt);
gr.DrawImage(original, dest_rectangle,
source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox2.Image = area;
}
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
if(original != null)
{
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "jpg files (*.jpg)|*.jpg|All files(*.*)|*.*";
if(dialog.ShowDialog() == DialogResult.OK)
{
original = new Bitmap(dialog.FileName);
pictureBox1.Image = new Bitmap(original, new Size(pictureBox1.Width, pictureBox1.Height));
}
dialog.Dispose();
}
}
I think your problem is the 'original' image size which is not the same as the picturebox size. Try this code to compensate for the zoom ratio between your 'original' image and the picturebox size:
// Draw the rectangle.
float zoomX = (float)original.Size.Width / pictureBox1.Width;
float zoomY = (float)original.Size.Height / pictureBox1.Height;
using (Graphics gr = Graphics.FromImage(bm))
{
gr.DrawRectangle(Pens.Red,
Math.Min(x0, x1) * zoomX, Math.Min(y0, y1) * zoomY,
Math.Abs(x0 - x1) * zoomX, Math.Abs(y0 - y1) * zoomY
);
}
This fixes the red rectangle in my case. But the copied part in picturebox2 is still not correct...
And this fixes the copy to the second picturebox:
// Copy the selected part of the image.
float zoomX = (float)original.Size.Width / pictureBox1.Width;
float zoomY = (float)original.Size.Height / pictureBox1.Height;
int wid = (int)(zoomX * Math.Abs(x0 - x1));
int hgt = (int)(zoomY * Math.Abs(y0 - y1));
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics gr = Graphics.FromImage(area))
{
Rectangle source_rectangle =
new Rectangle((int)(zoomX * Math.Min(x0, x1)), (int)(zoomY * Math.Min(y0, y1)),
wid, hgt);
Rectangle dest_rectangle =
new Rectangle(0, 0, wid, hgt);
gr.DrawImage(original, dest_rectangle,
source_rectangle, GraphicsUnit.Pixel);
}
I have a image in a picture box.it contains a Triangle.
I have a another picture box that contain a little Circle. i should put Circle on top of Triangle . i Zoom first image(Triangle ) to find top of it and then put Circle there.i do it correctly . but when i reset zoom , top of Triangle will be lose and Circle will be on a wrong position.
my code for zoom:
protected override void OnMouseWheel(MouseEventArgs e)
{
this.Cursor = Cursors.Default;
float oldzoom = zoom;
if (e.Delta > 0)
{
zoom += 0.625f;
zoomPerectNum += 50;
_txt_precentZoom.Text = zoomPerectNum.ToString() + "%";
}
else if (e.Delta < 0)
{
// zoom = Math.Max(zoom - 1F, 1F);
zoom = zoom - 0.625F;
if (zoom < 0.2503874F)
{
zoom = 0.2503874F;
}
else
{
zoomPerectNum -= 50;
_txt_precentZoom.Text = zoomPerectNum.ToString() + "%";
}
}
MouseEventArgs mouse = e as MouseEventArgs;
Point mousePosNow = mouse.Location;
int x = mousePosNow.X - _pic_image.Location.X; // Where location of the mouse in the pictureframe
int y = mousePosNow.Y - _pic_image.Location.Y;
int oldimagex = (int)(x / oldzoom); // Where in the IMAGE is it now
int oldimagey = (int)(y / oldzoom);
int newimagex = (int)(x / zoom); // Where in the IMAGE will it be when the new zoom i made
int newimagey = (int)(y / zoom);
imgx = newimagex - oldimagex + imgx; // Where to move image to keep focus on one point
imgy = newimagey - oldimagey + imgy;
_pic_image.Refresh(); // calls imageBox_Paint
}
private void imageBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.ScaleTransform(zoom, zoom);
if (img != null)
{
e.Graphics.DrawImage(img, imgx, imgy);
}
}
_pic_Circle:
private void _pic_Circle_MouseDown(object sender, MouseEventArgs e)
{
dragging = true;
dragPoint = new Point(e.X, e.Y);
}
private void _pic_Circle_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
_pic_Circle.Location = new Point(_pic_Circle.Location.X + e.X - dragPoint.X, _pic_Circle.Location.Y + e.Y - dragPoint.Y);
}
}
private void _pic_Circle_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
}