1

我创建了一种在拖放时移动 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);
4

2 回答 2

1

采用

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

代替

var dragImage = (Bitmap)picBox.Image;

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

于 2013-01-11T15:37:18.767 回答
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

于 2013-01-11T15:40:35.083 回答