In the last few months I’ve been working on an application, and one of it’s functions is that it can crop images. So, I’ve coded a function that draws a transparent orange rectangle, to show the user the crop area, but it works very slowly – can anyone help me/show me a way to make it faster?
Here is the code:
Image source;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
mousePos = e.Location;
}
Point mousePos;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
Image editSource = new Bitmap(source);
Graphics g = Graphics.FromImage(editSource);
SolidBrush brush = new SolidBrush(
Color.FromArgb(128, Color.Orange.R, Color.Orange.G, Color.Orange.B));
int width = e.X - mousePos.X;
if (width < 0) {
width *= -1;
}
int height = e.Y - mousePos.Y;
if (height < 0) {
height *= -1;
}
Size cropRectSize = new Size(width, height);
Rectangle cropRect = new Rectangle(mousePos, cropRectSize);
g.FillRectangle(brush, cropRect);
pictureBox1.Image = editSource;
}
}
So, all recommendations for not using picture box aside… I’ll give you a method to doing it 😉
The idea behind this is to only use mouse move, mouse down, etc to store what should be drawn. Then when it’s time to draw it use the stored state. This draws an orange rectangle whenever you have the mouse depressed on the picture box (even though recommendation is to not use picture box this same approach can be used for other surfaces.).