我拖动时拖放移动PictureBox-图像大小

时间:2013-01-11 15:28:18

标签: c# visual-studio

我创建了一个在拖放时移动PictureBox的方法。但是,当我拖动PictureBox时,图像具有真实的图像大小,我想图像的大小为PictureBox

 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);

2 个答案:

答案 0 :(得分:1)

使用

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

而不是

var dragImage = (Bitmap)picBox.Image;

(也许稍后可以在临时图像上调用Dispose,但如果不这样做,GC会处理它)

答案 1 :(得分:0)

这是因为图片框中的图像是全尺寸图像。图片框只是为了显示目的而缩放它,但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