//获取一条向量与矩形交点,0没有交点,1有一个交点,2有两个交点
- (CGPoint*)getIntersectionPointWithLine:(CGPoint)start end:(CGPoint)end andRect:(CGRect)rect {
//初始化一个数组保存结果
CGPoint *result = malloc(sizeof(CGPoint)*4);
result[0] = CGPointMake(-1, -1);
result[1] = CGPointMake(-1, -1);
result[2] = CGPointMake(-1, -1);
result[3] = CGPointMake(-1, -1);
CGFloat ox = rect.origin.x;
CGFloat oy = rect.origin.y;
CGFloat ow = rect.size.width;
CGFloat oh = rect.size.height;
CGPoint lt = CGPointMake(ox, oy);
CGPoint rt = CGPointMake(ox + ow, oy);
CGPoint lb = CGPointMake(ox, oy + oh);
CGPoint rb = CGPointMake(ox + ow, oy + oh);
CGPoint top = [self getIntersectionPointWithL1p1:start l1p2:end l2p1:lt l2p2:rt];
CGPoint left = [self getIntersectionPointWithL1p1:start l1p2:end l2p1:lt l2p2:lb];
CGPoint bottom = [self getIntersectionPointWithL1p1:start l1p2:end l2p1:lb l2p2:rb];
CGPoint right = [self getIntersectionPointWithL1p1:start l1p2:end l2p1:rt l2p2:rb];
int count = 0;
if (top.x != -1 && top.y != -1) {
result[count++] = top;
}
if (left.x != -1 && left.y != -1) {
result[count++] = left;
}
if (right.x != -1 && right.y != -1) {
result[count++] = right;
}
if (bottom.x != -1 && bottom.y != -1) {
result[count++] = bottom;
}
return result;
}
//获取两条线的交点
- (CGPoint)getIntersectionPointWithL1p1:(CGPoint)point1 l1p2:(CGPoint)point2 l2p1:(CGPoint)point3 l2p2:(CGPoint)point4 {
//A1x+B1y+C1 = 0 A2x+B2y+C2 = 0
float A1,B1,C1,A2,B2,C2;
getABCFunWith(point1.x, point1.y, point2.x, point2.y, &A1, &B1, &C1);
getABCFunWith(point3.x, point3.y, point4.x, point4.y, &A2, &B2, &C2);
//交点
float x = FLT_MIN,y = FLT_MIN;
getPointOfTwoLine(A1, B1, C1, A2, B2, C2, &x, &y);
if (x != FLT_MIN && y != FLT_MIN) {
}
// return CGPointMake(x, y); //如果不用判断是否在线段内则直接return
//判断是否在两个线段上,第3,4点为rect的边界
// BOOL inLine1 = judegePointInLine(x, y, point1.x, point1.y, point2.x, point2.y);
BOOL inLine2 = judegePointInLine(x, y, point3.x, point3.y, point4.x, point4.y);
if (inLine2) {
return CGPointMake(x, y);
} else {
return CGPointMake(-1, -1);
}
}
//判断是否在线段内
bool judegePointInLine(float px,float py , float p1x,float p1y,float p2x,float p2y) {
float minL1x = MIN(p1x, p2x);
float maxL1x = MAX(p1x, p2x);
float minL1y = MIN(p1y, p2y);
float maxL1y = MAX(p1y, p2y);
if (px < minL1x || px > maxL1x || py < minL1y || py > maxL1y) {
return false;
} else {
return true;
}
}
//获取两条线的交点坐标 输入两条直线点一般式方程
void getPointOfTwoLine(float a1,float b1 ,float c1, float a2 ,float b2 ,float c2, float *x ,float *y) {
if (a1*b2 == a2*b1) { //平行
return;
}
if (a1/a2 == b1/b2 && a1/a2 == c1/c2 && b1/b2 == c1/c2) { //重合
return;
}
*x = (c1 * b2 - c2 * b1) / (a2 * b1 - a1 * b2);
*y = (a2 * c1 - a1 * c2) / (a1 * b2 - a2 * b1);
NSLog(@"x = %f y = %f",*x,*y);
}
//一般式方程 Ax+By+C=0 (y2-y1)x + (x1-x2)y +x2y1 -x1y2 = 0 , A = Y2 - Y1 B = X1 - X2 C = X2*Y1 - X1*Y2
void getABCFunWith(float x1,float y1,float x2,float y2,float* a ,float* b,float* c) {
*a = y2 - y1;
*b = x1 - x2;
*c = x2*y1 - x1*y2;
NSLog(@"a = %f b = %f c = %f",*a,*b,*c);
}
网友评论