C#中級 コーディング例
G12)円外部点から接線点
円外部点から接線点
public static bool GetTangentPoints(
double px, double py, // 外部点 P
double cx, double cy, // 円の中心 C
double r, // 半径
out PointF t1, out PointF t2)
{
double dx = cx - px;
double dy = cy - py;
// P と C が同じなら接線は引けない
if (dx == 0 && dy == 0)
{
t1 = t2 = PointF.Empty;
return false;
}
double pc2 = dx * dx + dy * dy;
double pc = Math.Sqrt(pc2);
// 外部点が円の内側なら接線は存在しない
if (pc < r)
{
t1 = t2 = PointF.Empty;
return false;
}
// Circle intersection の幾何式を利用
double r2 = pc2 - r * r;
double d = r2 / pc; // P→X0 の距離
double h = Math.Sqrt(r2 - d * d); // 垂線の長さ
// X0 は P から C 方向に d だけ進んだ点
double x0 = px + dx * d / pc;
double y0 = py + dy * d / pc;
// 接点2つ
double rx = -dy * (h / pc);
double ry = dx * (h / pc);
t1 = new PointF((float)(x0 + rx), (float)(y0 + ry));// 片方(例えば「上」)
t2 = new PointF((float)(x0 - rx), (float)(y0 - ry));// もう片方(「下」)
return true;
}
外部点が円の内側なら、「false」を返す。
赤点 外部点p、橙点 円の中心c、青点 接線の点t1・t2