在过去的几个月里,我一直致力于一个应用程序,其中一个功能是它可以裁剪图像。所以,我编写了一个绘制透明橙色矩形的函数,向用户显示裁剪区域,但它的工作速度非常慢 - 任何人都可以帮助我/给我一个让它更快的方法吗?
以下是代码:
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;
}
}
答案 0 :(得分:5)
使其更快的方法是不要在鼠标移动时创建位图。如果需要在图形表面上绘图,请不要创建新的位图。
答案 1 :(得分:3)
MouseMove
仅invalidate已更改的区域答案 2 :(得分:2)
所以,所有关于不使用图片框的建议......我会给你一个方法来实现它;)
这背后的想法是仅使用鼠标移动,鼠标按下等来存储应该绘制的内容。然后在绘制时使用存储状态。只要您在图片框上按下鼠标,就会绘制橙色矩形(即使建议不使用图片框,也可以将此方法用于其他表面。)。
Point startPoint;
Point currentPoint;
bool draw = false;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
startPoint = e.Location;
draw = true;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
currentPoint = e.Location;
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (draw)
{
int startX = Math.Min(startPoint.X, currentPoint.X);
int startY = Math.Min(startPoint.Y, currentPoint.Y);
int endX = Math.Max(startPoint.X, currentPoint.X);
int endY = Math.Max(startPoint.Y, currentPoint.Y);
e.Graphics.DrawRectangle(Pens.Orange, new Rectangle(startX, startY, endX-startX, endY-startY));
}
}