如何创build几个沿path/ BezierCurve的UIButton?
我如何沿path创build对象/ BezierCurve? 换句话说,我怎样才能创build几个UIButtons沿给定的path,给定的时间间隔沿同一path?
我看到了几十个关于移动物体的问题。 但是我需要一个解决scheme来实际创build它们。
我想沿着path走,并为每个X点/距离创build一个对象。 喜欢这个:
....@....@....@....@....
在这种情况下,每4点获得一个位置,并在那里创build一个UIButton。
iOS没有一个公共的API,直接给你沿path间隔点。 但有一个迂回的方法来做到这一点。 假设你想沿着path上的点间隔X的距离。
首先,创build一个包含你的path的CGPathRef
。 (如果您愿意,可以构build一个UIBezierPath
,然后获取其CGPath
属性。)
然后,使用{ X, X }
的虚线模式调用CGPathCreateCopyByDashingPath
。 例如:
static CGFloat const kSpace = 10; CGPathRef dashedPath = CGPathCreateCopyByDashingPath(path, NULL, 0, (CGFloat const []){ kSpace, kSpace }, 2);
这将返回一个包含多个子path的新path。 每个子path是原始path的长度X段,并且沿着原始path与其相邻子path分开X的距离。 因此,子path的端点沿着原始path间隔长度为X的间隔。
因此,最后,使用CGPathApply
枚举虚线path,select端点并在那里创buildbutton。 首先,你需要把它封装在一个带有块的函数中:
static void applyBlockToPathElement(void *info, const CGPathElement *element) { void (^block)(const CGPathElement *) = (__bridge void (^)(const CGPathElement *))(info); block(element); } void MyCGPathApplyBlock(CGPathRef path, void (^block)(const CGPathElement *element)) { CGPathApply(path, (__bridge void *)(block), applyBlockToPathElement); }
然后,您可以应用一个find每个子path端点的块,并在那里创build一个button。 假设你有一个名为createButtonAtPoint:
的方法createButtonAtPoint:
像这样的东西应该工作:
__block BOOL isInSubpath = NO; __block CGPoint subpathStart = CGPointZero; __block CGPoint currentPoint = CGPointZero; MyCGPathApplyBlock(dashedPath, ^(const CGPathElement *element) { switch (element->type) { case kCGPathElementMoveToPoint: if (isInSubpath) { [self createButtonAtPoint:currentPoint]; isInSubpath = NO; } currentPoint = element->points[0]; break; case kCGPathElementCloseSubpath: // This should not appear in a dashed path. break; case kCGPathElementAddLineToPoint: case kCGPathElementAddQuadCurveToPoint: case kCGPathElementAddCurveToPoint: if (!isInSubpath) { [self createButtonAtPoint:currentPoint]; isInSubpath = YES; } int pointIndex = element->type == kCGPathElementAddLineToPoint ? 0 : element->type == kCGPathElementAddQuadCurveToPoint ? 1 : /* element->type == kCGPathElementAddCurveToPoint ? */ 2; currentPoint = element->points[pointIndex]; break; } });
你有没有解决你的问题呢? 如果没有,请看这个,如果它可以帮助
//if the interval is kown as float, suggesting it named padding //then you can for(i=0;i<numOfPaddings;i++){ //create a button UIButton *aButton = [UIButton buttonWithType:UIButtonRoundRect/*I forgot how to spell,but it does not metter*/]; //Set your button's position base on padding [aButton setFrame:CGRectMake(padding+padding*i,20,50,20)]; }