在C#中等效的Rectangle2D .outcode?

时间:2016-03-18 16:41:45

标签: java c# geometry

正如标题所说:C#中Java的.outcode是什么?

爪哇:

public static final Rectangle2D.Double gameField 
    = new Rectangle2D.Double(18, 18, 764, 564);

gameField.outcode(something)

C#:

public RectangleF gameField= new RectangleF(18, 18, 764, 564);
gameField.???

1 个答案:

答案 0 :(得分:1)

由于.NET RectangleF没有这个outcode(),我写了一个基本相同的。

public enum RectOut
{
    Left = 1,
    Top = 2,
    Right = 4,
    Bottom = 8,
}

public static class RectangleFExtensions
{
    public static int Outcode(this RectangleF rect, PointF point)
    {
        int outcode = 0;

        if (rect.Width <= 0) outcode |= (int)RectOut.Left | (int)RectOut.Right;
        if (rect.Height <= 0) outcode |= (int)RectOut.Top | (int)RectOut.Bottom;
        if (point.Y < rect.Top) outcode |= (int)RectOut.Top;
        if (point.Y > rect.Bottom) outcode |= (int)RectOut.Bottom;
        if (point.X < rect.Left) outcode |= (int)RectOut.Left;
        if (point.X > rect.Right) outcode |= (int)RectOut.Right;

        return outcode;
    }
}

用法:

RectangleF rect = new RectangleF(18f, 18f, 764f, 564f);
int outcode = rect.Outcode(new PointF(18f, 18f));

这是demo

修改:当点位于右下方时,显然RectangleF.Contains会返回false。更新了代码以不使用Contains()