我需要找到从圆和矩形的交点创建的最大弧。我有圆的中心,半径和矩形的坐标,我需要找到交点与圆心的角度。
我有一个可行的代码,但它计算迭代圆周点的解决方案,我想知道是否有更优雅的方法来使用三角法计算解决方案而不是"蛮力&# 34。
那是我的代码:
import 'dart:math';
class CircleTheSquare {
final Point _circleCenter;
final int _circleRadius;
final Rectangle _box;
CircleTheSquare(this._circleCenter, this._circleRadius, this._box);
Map<String, double> get arc {
Map res = new Map();
double angle = .0;
double angleIn;
double angleOut;
double increment = 1.0;
while (true) {
if (angle > 360.0 && angleIn == null) {
break;
}
// Finds a point of intersection (next points will be inside
// of the rectangle).
if (!_isOutside(angle) && _isOutside(angle - increment)) {
angleIn = angle;
}
// Finds next intersection (next points will be outside
// of the rectangle).
if (angleIn != null &&
_isOutside(angle + increment) && !_isOutside(angle)) {
angleOut = angle;
// Adds the arc to result only there's not a previous largest arc.
if (res["in"] == null ||
angleOut - angleIn > res["arc"]) {
res["in"] = angleIn;
res["arc"] = angleOut - angleIn;
}
angleIn = null;
angleOut = null;
}
angle += increment;
}
// If there's no intersections.
// -- For simplicity, we will assume that the
// rectangle and the circle intersect or that the circle is
// inside of the rectangle).
if (res["in"] == null) {
res = {"in" : 0.0, "arc" : 360.0};
}
return res;
}
bool _isOutside(double a) {
var res;
double cx = _circleCenter.x + (_circleRadius * cos(a * (PI / 180)));
double cy = _circleCenter.y + (_circleRadius * sin(a * (PI / 180)));
bool hOut = cx < _box.left || cx > _box.left + _box.width;
bool vOut = cy < _box.top || cy > _box.top + _box.height;
if (hOut || vOut) {
res = true;
} else {
res = false;
}
return res;
}
}
main() {
CircleTheSquare a = new CircleTheSquare(new Point(250, 250), 100,
new Rectangle(0,0,500,500));
print(a.arc); // {in: 0.0, arc: 360.0}
CircleTheSquare b = new CircleTheSquare(new Point(450, 250), 100,
new Rectangle(0,0,500,500));
print(b.arc); // {in: 60.0, arc: 240.0}
CircleTheSquare c = new CircleTheSquare(new Point(420, 420), 100,
new Rectangle(0,0,500,500));
print(c.arc); // 4 intersections, returns the largest arc:
// {in: 127.0, arc: 196.0}
}
答案 0 :(得分:3)
答案 1 :(得分:1)
如您所料,有更好,更直接的方法来解决这个问题。你可能想看看例如http://mathworld.wolfram.com/Circle-LineIntersection.html。将矩形拆分为线,获得每条线的交点,确定它们是否在实际线段内,然后找到给出最大弧的点。