易于使用的图像缩放和裁剪控件






4.68/5 (13投票s)
允许用户加载、调整大小和裁剪图像,无需其他程序的臃肿和复杂性。
问题
您需要允许您的桌面应用程序(WinForms)的用户在软件内部调整和/或裁剪大型图片,也许是为了允许他们上传需要统一尺寸或类型的专业头像。 安装和/或指导用户使用第三方软件不是一个选项。
解决方案
通常,我绝不会梦想创建另一个图像编辑程序。 然而,我发现自己处于一种境地,考虑到用户群,创建一种能够快速轻松地让用户裁剪用普通数码相机拍摄的人像照片的控件是有意义的。 这个解决方案的驱动力是防止人们上传尺寸和文件大小都过大的图片。
特点
- 易于使用的界面。
- 图像调整大小以“实时”完成;无需根据百分比猜测。
- 所需的图像尺寸可以在设计时或运行时设置。 确保用户将加载正确尺寸的图像。
- 支持加载和保存 BMP、JPG、GIF、PNG 和 TIF 文件。
- 最初将图像调整大小以适应工作区。
使用控件
只需将其拖放到表单并停靠即可开箱即用。 要将其集成到您的解决方案中,只需将其添加到您的表单,订阅 WorkComplete
事件,然后调用 GetEditedImage
。
imageResizer1.WorkComplete +=
new ImageResizer.WorkCompleteDelegate(imageResizer1_WorkComplete);
void imageResizer1_WorkComplete(object sender, bool complete)
{
if (complete)
{
pictureBox1.Image = imageResizer1.GetEditedImage();
// your processing here...
}
else // user cancelled
{
pictureBox1.Image = null;
}
imageResizer1.Reset();
imageResizer1.Visible = false;
pictureBox1.Visible = true;
}
关注点
通常,在表单的 Paint
事件中进行自定义绘制是一件痛苦的事情。 然而,我通过使用 GroupBox
来跟踪工作区的尺寸“作弊”了。 GroupBox
被锚定,因此当控件调整大小时,我的坐标会自动跟踪,我无需担心绘制超出边界。
private void ImageResizer_Paint(object sender, PaintEventArgs e)
{
// Draws alternating shaded rectangles so user
// can differentiate canvas from image.
bool xGrayBox = true;
int backgroundX = 0;
while (backgroundX < grpImage.Width)
{
int backgroundY = 0;
bool yGrayBox = xGrayBox;
while (backgroundY < grpImage.Height)
{
int recWidth = (int)((backgroundX + 50 > grpImage.Width) ?
grpImage.Width - backgroundX : 50);
int recHeight = (int)((backgroundY + 50 > grpImage.Height) ?
grpImage.Height - backgroundY : 50);
e.Graphics.FillRectangle(((Brush)(yGrayBox ?
Brushes.LightGray : Brushes.Gainsboro)),
backgroundX, backgroundY, recWidth + 2, recHeight + 2);
backgroundY += 50;
yGrayBox = !yGrayBox;
}
backgroundX += 50;
xGrayBox = !xGrayBox;
}
if (!SuspendRefresh && DrawnImage != null)
{
// if the image is too large, draw only visible portion
// as dictated by the scrollbars, otherwise draw the whole image.
if (DrawnImage.Width > grpImage.Width ||
DrawnImage.Height > grpImage.Height)
{
int rectX = 0;
if (hsbImage.Value > 0)
{
rectX = hsbImage.Value;
}
int rectY = 0;
if (vsbImage.Value > 0)
{
rectY = vsbImage.Value;
}
e.Graphics.DrawImage(DrawnImage, 0, 0,
new Rectangle( rectX, rectY, grpImage.Width, grpImage.Height),
GraphicsUnit.Pixel);
}
else
{
e.Graphics.DrawImage(DrawnImage, 0, 0);
}
// Draw the crop rectangle with both yellow and black
// so it is easily visible no matter the image.
if (chkCrop.Checked)
{
e.Graphics.DrawRectangle(Pens.Yellow, CropBoxX,
CropBoxY, (float)nudCropWidth.Value, (float)nudCropHeight.Value);
e.Graphics.DrawRectangle(Pens.Black, CropBoxX - 1, CropBoxY - 1,
(float)nudCropWidth.Value + 2, (float)nudCropHeight.Value + 2);
}
}
}
历史
- 2008年10月29日:初始发布
- 2008年10月31日:更新下载文件