最簡單的方法採用的是用DrawToBitmap方法從不管SizeMode
的圖片框的產量,然後裁剪該輸出是這樣的:
public static Bitmap Crop(PictureBox pb, int x, int y, int w, int h)
{
var rect = pb.ClientRectangle;
using (var output = new Bitmap(rect.Width, rect.Height, pb.Image.PixelFormat))
{
pb.DrawToBitmap(output, rect);
return output.Clone(new Rectangle(x, y, w, h), output.PixelFormat);
}
}
但是,上述方法的缺點是它真的會裁剪潛在縮放的圖像。
如果您確實想裁剪原始圖像,則需要將傳遞的矩形(我假設它在圖片框客戶端座標中)映射到原始圖像座標。
如果圖片框提供了一種方法ClientToImage
(類似於ClientToScreen
),但它沒有這將是很好的,所以我們需要從Reference Source提取SizeMode
邏輯。
新的方法是這樣的:
public static class ImageUtils
{
public static Bitmap CropImage(this PictureBox pb, int x, int y, int w, int h)
{
var imageRect = pb.GetImageRectangle();
var image = pb.Image;
float scaleX = (float)image.Width/imageRect.Width;
float scaleY = (float)image.Height/imageRect.Height;
var cropRect = new Rectangle();
cropRect.X = Scale(x - imageRect.X, scaleX, image.Width);
cropRect.Y = Scale(y - imageRect.Y, scaleY, image.Height);
cropRect.Width = Scale(w, scaleX, image.Width - cropRect.X);
cropRect.Height = Scale(h, scaleY, image.Height - cropRect.Y);
var result = new Bitmap(cropRect.Width, cropRect.Height, image.PixelFormat);
using (var g = Graphics.FromImage(result))
g.DrawImage(image, new Rectangle(new Point(0, 0), cropRect.Size), cropRect, GraphicsUnit.Pixel);
return result;
}
static int Scale(int value, float scale, int maxValue)
{
int result = (int)(value * scale);
return result < 0 ? 0 : result > maxValue ? maxValue : result;
}
public static Rectangle GetImageRectangle(this PictureBox pb)
{
var rect = pb.ClientRectangle;
var padding = pb.Padding;
rect.X += padding.Left;
rect.Y += padding.Top;
rect.Width -= padding.Horizontal;
rect.Height -= padding.Vertical;
var image = pb.Image;
var sizeMode = pb.SizeMode;
if (sizeMode == PictureBoxSizeMode.Normal || sizeMode == PictureBoxSizeMode.AutoSize)
rect.Size = image.Size;
else if (sizeMode == PictureBoxSizeMode.CenterImage)
{
rect.X += (rect.Width - image.Width)/2;
rect.Y += (rect.Height - image.Height)/2;
rect.Size = image.Size;
}
else if (sizeMode == PictureBoxSizeMode.Zoom)
{
var imageSize = image.Size;
var zoomSize = pb.ClientSize;
float ratio = Math.Min((float)zoomSize.Width/imageSize.Width, (float)zoomSize.Height/imageSize.Height);
rect.Width = (int)(imageSize.Width * ratio);
rect.Height = (int)(imageSize.Height * ratio);
rect.X = (pb.ClientRectangle.Width - rect.Width)/2;
rect.Y = (pb.ClientRectangle.Height - rect.Height)/2;
}
return rect;
}
}
技術上你是不是裁剪'Bitmap'對象,但圖片框的輸出,這除了'SizeMode'正常或自動調整大小是不同的。 –