【发布时间】:2012-03-02 01:19:50
【问题描述】:
在 iOS 中,我试图确定矩形上的点,该点与从中心点到矩形周边的假想线以预定角度相交。
假设我知道中心点、矩形的大小和角度(从东方的 0 度开始,逆时针经过北方的 90 度、西方的 180 度和南方的 270 度,再到东方的 360 度)。我需要知道相交点的坐标。
Finding points on a rectangle at a given angle 上的(对我而言)有点令人困惑的数学但大概是准确的答案让我尝试了以下代码,但它不能正常工作。这个问题与那个问题类似,但我正在寻找一种更正的 Objective-C / iOS 方法,而不是一般的数学答案。
我认为部分代码问题与使用单个 0 到 360 度角(以弧度表示,不可能为负数)输入有关,但可能还有其他问题。下面的代码主要使用the answer from belisarius 中定义的符号,包括我尝试为其中定义的四个区域中的每一个计算相交点。
这段代码在我的 UIImageView 子类中:
- (CGPoint) startingPointGivenAngleInDegrees:(double)angle {
double angleInRads = angle/180.0*M_PI;
float height = self.frame.size.height;
float width = self.frame.size.width;
float x0 = self.center.x;
float y0 = self.center.y;
// region 1
if (angleInRads >= -atan2(height, width) && angleInRads <= atan2(height, width)) {
return CGPointMake(x0 + width/2, y0 + width/2 * tan(angleInRads));
}
// region 2
if (angleInRads >= atan2(height, width) && angleInRads <= M_PI - atan2(height, width)) {
return CGPointMake(x0 + height / (2*tan(angleInRads)),y0+height/2);
}
// region 3
if (angleInRads >= M_PI - atan2(height, width) && angleInRads <= M_PI + atan2(height, width)) {
return CGPointMake(x0 - width/2, y0 + width/2 * tan(angleInRads));
}
// region 4
return CGPointMake(x0 + height / (2*tan(angleInRads)),y0-height/2);
}
【问题讨论】:
标签: iphone ios math graphics geometry