簡體   English   中英

從WPF中的圖像裁剪對角線區域

[英]Crop a diagonal area from an image in WPF

我想在畫布上使用用戶繪制的矩形從圖像中裁剪。 矩形可以移動,調整大小和旋轉。

當用戶選擇“獲取裁剪的圖像”時,矩形內的區域應保存在頁面上的第二個圖像位置,只要矩形不旋轉,我可以做得很好。 (直接使用CroppedBitmap。)但是,當矩形成一定角度時,我不知道如何執行裁剪。

這就是我想要做的(原諒我糟糕的MS Paint技能):

圖像裁剪到旋轉的矩形區域。

我的問題是:

1)如何正確跟蹤或計算矩形的點?

和,

2)一旦有了點,如何裁剪旋轉的矩形?

編輯:感謝用戶Rotem ,我相信我已經回答了第二個問題。 使用從以下答案中修改的代碼: 答案1答案2 ,我看到了很好的結果。 不幸的是,我仍然無法跟蹤矩形的正確位置點,所以到目前為止我還不能完全測試它。

public static Bitmap CropRotatedRect(Bitmap source, System.Drawing.Rectangle rect, float angle, bool HighQuality)
 {
    Bitmap result = new Bitmap((int)rect.Width, (int)rect.Height);
    using (Graphics g = Graphics.FromImage(result))
     {
        g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
        using (Matrix mat = new Matrix())
         {
            mat.Translate(-rect.Location.X, -rect.Location.Y);
            mat.RotateAt(-(angle), rect.Location);
            g.Transform = mat;
            g.DrawImage(source, new System.Drawing.Point(0, 0));
         }
     }
    return result;
 }

編輯:第一點的答案比我原來想的要容易得多。 您始終可以通過調用以下命令獲取矩形的左上角:

double top = Canvas.GetTop(rect);
double left = Canvas.GetLeft(rect);

然后,您可以使用寬度和高度來計算其余的點,

Point topLeft = new Point(left, top);
Point topRight = new Point(left + rect.Width, top);
Point bottomLeft = new Point(left, top + rect.Height);
Point bottomRight = new Point(left + rect.Width, top + rect.Height);
Point centerPoint = new Point(left + (rect.Width / 2), top + (rect.Height / 2));

如果旋轉了矩形,則必須平移這些點以確定它們在畫布上的真正位置-

public Point TranslatePoint(Point center, Point p, double angle)
 { 
    // get the point relative to (0, 0) by subtracting the center of the rotated shape.
    Point relToOrig = new Point(p.X - center.X, p.Y - center.Y);
    double angleInRadians = angle * Math.PI / 180;
    double sinOfA = Math.Sin(angleInRadians);
    double cosOfA = Math.Cos(angleInRadians);
    Point translatedPoint = new Point(relToOrig.X * cosOfA - relToOrig.Y * sinOfA,
                                      relToOrig.X * sinOfA + relToOrig.Y * cosOfA);
    return new Point(translatedPoint.X + center.X, translatedPoint.Y + center.Y);
 }

一旦能夠平移左上角,就可以使用Rotem的裁剪方法。 您還可以計算矩形其余部分的位置,因此可以確定矩形是否在圖像的邊界內,是否接觸到邊緣或您可能要針對其他任何事情進行處理位置。

我找到了自己的問題的答案,並在此過程中進行了適當的編輯。 請參閱上面的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM