拖放,当我拖动来移动图像的大小PictureBox-(Drag and Drop move Pict

2019-10-17 14:10发布

我创建了当我拖放其移动图片框的方法。 但是,当我拖动图片框,图像具有图像的真实大小,我想图像具有图片框的大小

 private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            picBox = (PictureBox)sender;
            var dragImage = (Bitmap)picBox.Image;
            IntPtr icon = dragImage.GetHicon();
            Cursor.Current = new Cursor(icon);
            DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
            DestroyIcon(icon);
        }
    }

protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
    {
        e.UseDefaultCursors = false;
    }
    protected override void OnDragEnter(DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(Bitmap))) e.Effect = DragDropEffects.Copy;
    }
    protected override void OnDragDrop(DragEventArgs e)
    {

        picBox.Location = this.PointToClient(new Point(e.X - picBox.Width / 2, e.Y - picBox.Height / 2));
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    extern static bool DestroyIcon(IntPtr handle);

Answer 1:

采用

var dragImage = new Bitmap((Bitmap)picBox.Image, picBox.Size);

代替

var dragImage = (Bitmap)picBox.Image;

(也许调用Dispose临时图像后,但如果你不这样做,GC将处理它)



Answer 2:

这是因为在你的图片框的图像是全尺寸的图像。 图片框只是其刻度显示为目的,但在Image属性具有原始大小的图像。

所以,在你MouseDown事件处理程序,你要使用它之前调整图像大小。

而不是:

var dragImage = (Bitmap)picBox.Image;

尝试:

 var dragImage = ResizeImage(picBox.Image, new Size(picBox.Width, PicBox.Height));

使用这样的方法来调整图片的大小为您提供:

public static Image ResizeImage(Image image, Size size, 
    bool preserveAspectRatio = true)
{
    int newWidth;
    int newHeight;
    if (preserveAspectRatio)
    {
        int originalWidth = image.Width;
        int originalHeight = image.Height;
        float percentWidth = (float)size.Width / (float)originalWidth;
        float percentHeight = (float)size.Height / (float)originalHeight;
        float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
        newWidth = (int)(originalWidth * percent);
        newHeight = (int)(originalHeight * percent);
    }
    else
    {
        newWidth = size.Width;
        newHeight = size.Height;
    }
    Image newImage = new Bitmap(newWidth, newHeight);
    using (Graphics graphicsHandle = Graphics.FromImage(newImage))
    {
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
    }
    return newImage;
}

从这里 * 图像大小调整代码: http://www.codeproject.com/Articles/191424/Resizing-an-Image-On-The-Fly-using-NET



文章来源: Drag and Drop move PictureBox- size of image when I'm dragging