需要做的是向矩陣對齊添加偏移量。在這種情況下,我從每邊(總共9個矩形)取出一個額外長度的矩形,並每次偏移矩陣。
請注意,有必要將抵消0
(原始作物)放在最後,否則您將得到錯誤的結果。
另請注意,如果您指定的矩形大於旋轉後的圖片,您仍然會看到空白區域。
public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle, bool HighQuality)
{
int[] offsets = { -1, 1, 0 }; //place 0 last!
Bitmap result = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(result))
{
g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
foreach (int x in offsets)
{
foreach (int y in offsets)
{
using (Matrix mat = new Matrix())
{
//create the appropriate filler offset according to x,y
//resulting in offsets (-1,-1), (-1, 0), (-1,1) ... (0,0)
mat.Translate(-rect.Location.X - rect.Width * x, -rect.Location.Y - rect.Height * y);
mat.RotateAt(angle, rect.Location);
g.Transform = mat;
g.DrawImage(source, new Point(0, 0));
}
}
}
}
return result;
}
要重新創建例如:
Bitmap source = new Bitmap("C:\\mjexample.jpg");
Bitmap dest = CropRotatedRect(source, new Rectangle(86, 182, 87, 228), -45, true);
你爲什麼不想要旋轉的影像和作物是什麼?這顯然不應該是可見的,只需複製你的原始圖像。 – TJHeuvel 2012-01-09 08:32:22
添加一些調整大小的步驟,解釋仍然很複雜。 – CodingBarfield 2012-01-09 08:42:13
@TJHeuvel我完全不明白你所說的。旋轉圖像會改變尺寸,所以起點的位置也會改變。這就是爲什麼我不想旋轉圖像 – user1125953 2012-01-09 08:45:41