1
我用下面的代碼行段延伸至矩形的boundry的boundry,它如果矩形內的點,但如果有一個點出了矩形的boundry做工精良它失敗限制線段矩形
static void extend(Rectangle bounds, ref PointF start, ref PointF end)
{
if (start != end) // this to avoid small changes in orientation
{
float slope = (end.Y - start.Y)/(end.X - start.X);
if (Math.Round(start.Y, 2) == Math.Round(end.Y, 2) || Math.Abs(slope) <= 0.01d) // 0.01 is offset to check if the slope is very small
{
start.X = bounds.X;
start.Y = start.Y;
end.X = bounds.X + bounds.Width;
end.Y = end.Y;
return;
}
if (Math.Round(start.X, 2) == Math.Round(end.X, 2) || Math.Abs(slope) <= 0.01d)
{
start.X = start.X;
start.Y = bounds.Y;
end.X = end.X;
end.Y = bounds.Y + bounds.Height;
return;
}
// based on (y - y1)/(x - x1) == (y2 - y1)/(x2 - x1)
// => (y - y1) * (x2 - x1) == (y2 - y1) * (x - x1)
// y_for_xmin = y1 + (y2 - y1) * (xmin - x1)/(x2 - x1)
float y_for_xmin = start.Y + ((end.Y - start.Y) * (bounds.X - start.X)/(end.X - start.X));
// y_for_xmax = y1 + (y2 - y1) * (xmax - x1)/(x2 - x1)
float y_for_xmax = start.Y + ((end.Y - start.Y) * (bounds.X + bounds.Width - start.X)/(end.X - start.X));
// x_for_ymin = x1 + (x2 - x1) * (ymin - y1)/(y2 - y1)
float x_for_ymin = start.X + ((end.X - start.X) * (bounds.Y - start.Y)/(end.Y - start.Y));
//x_for_ymax = x1 + (x2 - x1) * (ymax - y1)/(y2 - y1)
float x_for_ymax = start.X + ((end.X - start.X) * (bounds.Y + bounds.Height - start.Y)/(end.Y - start.Y));
if ((bounds.Y <= y_for_xmin) && (y_for_xmin <= bounds.Y + bounds.Height))
{
if ((bounds.X <= x_for_ymax) && (bounds.X <= bounds.X + bounds.Width))
{
start.X = bounds.X;
start.Y = y_for_xmin;
end.X = x_for_ymax;
end.Y = bounds.Y + bounds.Height;
return;
}
if ((bounds.X <= x_for_ymin && x_for_ymin <= bounds.X + bounds.Width))
{
start.X = bounds.X;
start.Y = y_for_xmin;
end.X = x_for_ymin;
end.Y = bounds.Y;
return;
}
}
if ((bounds.Y <= y_for_xmax) && (bounds.Y <= bounds.Y + bounds.Height))
{
if ((bounds.X <= x_for_ymin) && (x_for_ymin <= bounds.X + bounds.Width))
{
start.X = x_for_ymin;
start.Y = bounds.Y;
end.X = bounds.X + bounds.Width;
end.Y = y_for_xmax;
return;
}
if ((bounds.X <= x_for_ymax) && (x_for_ymax <= bounds.X + bounds.Width))
{
start.X = x_for_ymax;
start.Y = bounds.Y + bounds.Height;
end.X = bounds.X + bounds.Width;
end.Y = y_for_xmax;
return;
}
}
}
}
任何想法如何解決線上的點的情況下出來的矩形
因爲你正在檢查它是否在矩形內..... –
如何檢查外部請處理 – AMH
@AMH:你想保留點在矩形外的位置? – Jiri