简体   繁体   中英

Correctly calculate bounding box for a transformed rectangle with System.Numerics

I'm using the following algorithm to calculate the bounding box for a transformed rectangle but it seems to have issues.

public static Rectangle GetBoundingRectangle(Rectangle rectangle, Matrix3x2 matrix)
{
    Vector2 leftTop = Vector2.Transform(new Vector2(rectangle.Left, rectangle.Top), matrix);
    Vector2 rightTop = Vector2.Transform(new Vector2(rectangle.Right, rectangle.Top), matrix);
    Vector2 leftBottom = Vector2.Transform(new Vector2(rectangle.Left, rectangle.Bottom), matrix);
    Vector2 rightBottom = Vector2.Transform(new Vector2(rectangle.Right, rectangle.Bottom), matrix);

    Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom));
    Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom));

    return new Rectangle(0, 0, (int)(max.X - min.X), (int)(max.Y - min.Y));
}

It works well with rotation but not with skew. As you will can see from the images below the rectangle calculated from the formula is too small. Can anyone spot what the issue is or is there a method already within the System.Numerics namespace that I can use?

Rotate - Matrix formula

Matrix3x2.CreateRotation(radians, origin)

具有正确边界框的旋转图像

Skew - Matrix formula

Matrix3x2.CreateRotation(radiansX, radiansY, origin)

边框错误的图像

I'm not sure exactly what the problem is with what you've done but it isn't representing the most robust definition of the bounding box which is this:

var allCorners = new List<Vector2> { leftTop, rightTop, leftBottom, rightBottom };
var xExtent = allCorners.Select(v => v.X).Max() - allCorners.Select(v => v.X).Min();
var yExtent = allCorners.Select(v => v.Y).Max() - allCorners.Select(v => v.Y).Min();
return new Rectangle(0, 0, xExtent, yExtent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM