用了两个晚上,生成灰度图片用到了ColorMatrix类,要设置一个5*5的参数矩阵,不懂那个在MSDN上抄了他的矩阵,在做拖动时有两个地方理解错误浪费了很多时间,记录在此:
1.拖进,e.Data.GetData(DataFormats.FileDrop)的参数一开始认为是DataFormats.Bitmap,返回的Data认为是Bitmap的数据其实错了,正确的代码如下:
private void flowLayoutPanel_原图片_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] fileList = (string[])(e.Data.GetData(DataFormats.Bitmap));
foreach (string fileName in fileList)
{
Image image = Image.FromFile(fileName);
PictureBox pictureBox = new PictureBox();
pictureBox.Size = new Size(this.PicWidth, this.PicHeight);
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox.Image = image;
FileInfo info = new FileInfo(fileName);
pictureBox.Tag = info.Name;
this.flowLayoutPanel1.Controls.Add(pictureBox);
}
}
}
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] fileList = (string[])(e.Data.GetData(DataFormats.Bitmap));
foreach (string fileName in fileList)
{
Image image = Image.FromFile(fileName);
PictureBox pictureBox = new PictureBox();
pictureBox.Size = new Size(this.PicWidth, this.PicHeight);
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox.Image = image;
FileInfo info = new FileInfo(fileName);
pictureBox.Tag = info.Name;
this.flowLayoutPanel1.Controls.Add(pictureBox);
}
}
}
2.拖出,认为拖出就是要把保存的数据放到一个DataObject中通过设置 DataFormats.bitmap格式表明数据类型,其实也错了。拖出实际上就是把要保存的数据保存成文件,然后将该文件的路径做为数据,使用DataFormats.FileDrop做为参数,这样就能完成拖出效果了。关键就是这一句 DoDragDrop(new DataObject(DataFormats.FileDrop, files),
DragDropEffects.Move /* | DragDropEffects.Link */);,注意files是string[]数组,我用一个string总是出不来,用了好久才找到这个原因。完整代码如下:
void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
PictureBox pictureBox = sender as PictureBox;
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
DataObject dataObject = new DataObject();
string imageName = pictureBox.Tag.ToString().Substring(0, pictureBox.Tag.ToString().LastIndexOf(".")) + "_gray" + pictureBox.Tag.ToString().Substring(pictureBox.Tag.ToString().LastIndexOf("."));
string fileName = this.CreateTemporaryFileName(imageName, pictureBox.Image);
string[] files = new string[1] { fileName };
DoDragDrop(new DataObject(DataFormats.FileDrop, files), DragDropEffects.Move /* | DragDropEffects.Link */);
}
}
}
{
PictureBox pictureBox = sender as PictureBox;
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
DataObject dataObject = new DataObject();
string imageName = pictureBox.Tag.ToString().Substring(0, pictureBox.Tag.ToString().LastIndexOf(".")) + "_gray" + pictureBox.Tag.ToString().Substring(pictureBox.Tag.ToString().LastIndexOf("."));
string fileName = this.CreateTemporaryFileName(imageName, pictureBox.Image);
string[] files = new string[1] { fileName };
DoDragDrop(new DataObject(DataFormats.FileDrop, files), DragDropEffects.Move /* | DragDropEffects.Link */);
}
}
}
贴个图吧: