iphone - 如何在iPhone SDK中找到闭合路径(两条线交点)?

标签 iphone ios uibezierpath

请看图片。如何获得两条线的交点(即绿色圆角点)?我想裁剪图像的内部部分。结束路径是该行中的任何位置。

context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, 1.0 * self.scale);
CGContextSetLineCap(context, kCGLineCapRound);
[[UIColor redColor] setStroke];

CGPoint firstPoint = CGPointFromString([self.touchPoints objectAtIndex:0]);
CGContextMoveToPoint(context, firstPoint.x, firstPoint.y);

for (NSString *pointString in self.touchPoints) {
    CGPoint point = CGPointFromString(pointString);
    CGContextAddLineToPoint(context, point.x, point.y);
}

CGContextStrokePath(context);

此代码用于绘制线条。线条画工作正常,裁剪也工作正常......但交点是我的主要问题。请帮我。

enter image description here

最佳答案

想法,检查以firSTLine<>laSTLine、firSTLine<>secondlaSTLine ...firSTLine<>thirdline => secondaryline<>laSTLine等开头的交集。这应该会给你最外面的交集。

以下代码未经测试,但应该可以帮助您解决问题。

typedef struct {
    CGPoint startPoint;
    CGPoint endPoint;
} Line;

#define CGPointNULL CGPointMake(NAN, NAN)

#define Line(_i_) {CGPointFromString(touchPoints[_i_-1]), CGPointFromString(touchPoints[_i_])};

CGPoint LineIntersects(Line *first, Line *second) {
    int x1 = first->startPoint.x; int y1 = first->startPoint.y;
    int x2 = first->endPoint.x; int y2 = first->endPoint.y;

    int x3 = second->startPoint.x; int y3 = second->startPoint.y;
    int x4 = second->endPoint.x; int y4 = second->endPoint.y;

    int d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);

    if (d == 0) return CGPointNULL;

    int xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
    int yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;

    return CGPointMake(xi,yi);
}

static inline BOOL CGPointIsValid(CGPoint p) {
    return (p.x != NAN && p.y != NAN);
}

- (CGPoint)mostOuterIntersection:(NSArray *)touchPoints {
    CGPoint intersection = CGPointNULL;
    int touchCount = [touchPoints count];

    for(int i = 1; i<touchCount; i++) {
        Line first = Line(i);
        for(int j = touchCount-1; j>i+1; j--) {
            Line last = Line(j);
            intersection = LineIntersects(&first, &last);
            if(CGPointIsValid(intersection)) {
                break;
            }
        }
    }
    return intersection;
}

关于iphone - 如何在iPhone SDK中找到闭合路径(两条线交点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909008/

相关文章:

iphone - iOS Phonegap 正则表达式替换

ios - 在 UIImage 中平滑地移动一个洞?

ios - Swift:使图像在 UIBezierPath(overInRect) 中连续循环

iphone - 闪屏时崩溃,iPhone

ios - 使用 SDK 4.0.1 的 Objective-C Facebook 登录

iphone - 用于检查 iOS 编译的 ARM 反汇编器/交叉编译器

ios - UIBezierPath自定义lineCapStyle两端均不同

iphone - 减少 UIViewController 的背景 "alpha"

iphone - FMOD 用完 channel ,FMOD_CHANNEL_FREE 似乎不起作用

ios - block 中的 objective-c block