---
title: "直线上求点"
author: "shicheng"
date: "2011-12-17T18:26:03Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2011-12-17T18:26:03Z"
id: 1314978
url: "https://benchild.iteye.com/blog/1314978"
---

![直线求点](http://dl.iteye.com/upload/attachment/607299/17a91858-749e-3184-9c9c-bac9d9aa832d.png)

问题描述：

以起点（x1，y1）和已知点（x2，y2）的直线上，求从起点开始，长度为r的点（所要求的点）的坐标

解决方案：

1.根据直线方程y=kx+b，可以求出k、b的值

2.根据圆的一般方程(x-a)^2+(y-b)^2=r^2,加上上面的公式，就可以计算出来了

实现代码：

```
public static short[] getStraightLinePoint(int x1, int y1, int x2, int y2,
			int radius) {
		short x3 = 0;
		short y3 = 0;
		float k = 0;
		float b = 0;

		if ((x2 - x1) == 0 && (y2 - y1 == 0)) {
			return null;
		}

		if ((x2 - x1) == 0) {
			if (y2 > y1) {
				x3 = (short) x1;
				y3 = (short) (y1 + radius);
				return new short[] { x3, y3 };
			} else {
				x3 = (short) x1;
				y3 = (short) (y1 - radius);
				return new short[] { x3, y3 };
			}
		}

		if ((y2 - y1 == 0)) {
			if (x2 > x1) {
				y3 = (short) y1;
				x3 = (short) (x1 + radius);
				return new short[] { x3, y3 };
			} else {
				y3 = (short) y1;
				x3 = (short) (x1 - radius);
				return new short[] { x3, y3 };
			}
		}

		k = (float) (y2 - y1) / (float) (x2 - x1);
		if (k == 0 || k * k + 1 == 0)
			return null;
		b = y1 - k * x1;
		double tmpV = Math.sqrt(Math.abs(((radius * radius - (y1 * y1 + b * b
				+ x1 * x1 - 2 * y1 * b)) + (k * b - x1 - k * y1)
				* (k * b - x1 - k * y1) / (k * k + 1))
				/ (k * k + 1)));
		double tmpV2 = (k * b - x1 - k * y1) / (k * k + 1);
		x3 = (short) (tmpV - tmpV2);
		if ((x2 < x1 && x3 > x1) || (x2 > x1 && x3 < x1)) {
			x3 = (short) (-tmpV - tmpV2);
		}
		y3 = (short) (x3 * k + b);
		return new short[] { x3, y3 };
	}
```

 

仅供参考！