![](/img/trans.png)
[英]Why when i drag with the mouse the image in the pictureBox it return the image to its original size?
[英]Drag and Drop move PictureBox- size of image when I'm dragging
我創建了一個在拖放時移動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);
采用
var dragImage = new Bitmap((Bitmap)picBox.Image, picBox.Size);
代替
var dragImage = (Bitmap)picBox.Image;
(也許稍后再調用該臨時映像上的Dispose,但如果您不這樣做,則GC會對其進行處理)
這是因為圖片框中的圖像是完整尺寸的圖像。 圖片框只是為了顯示目的對其進行縮放,但是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.