2013-01-11 138 views
1

我創建了一個方法,當我拖放時移動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); 
+0

你的意思是說你想讓圖像縮小以適應picturebox? –

+0

http://www.dotnetcurry.com/ShowArticle.aspx?ID=179 – MethodMan

+0

@glace是的,我需要縮小圖片框 – Ladessa

回答

1

使用

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

,而不是

var dragImage = (Bitmap)picBox.Image; 

(也許稍後調用臨時圖像,但GC會處理它,如果你不這樣做)

+0

thx很多!有用! – Ladessa

+0

如果圖像的寬高比與圖片框的寬高比不匹配,您需要自己計算正確的大小。由於jmrnet已經發布了包含它的答案,因此不會將其添加到我的答案中。隨意接受他接受的答案。 – Zarat

0

這是因爲圖片框中的圖像是全尺寸圖像。圖片框只是爲了顯示而縮放它,但Image屬性具有原始大小的圖像。

因此,在您的MouseDown事件處理程序中,您希望在使用它之前調整圖像的大小。

不是:

var dragImage = (Bitmap)picBox.Image; 

嘗試:

​​

使用這樣的方法來調整圖片的大小爲您提供:

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