获取UIBezierPath线上的所有点

1,091 阅读1分钟

一、项目用到贝塞曲线,需求需要曲线保存到服务器或者在另一个页面展示,当然截图也可以满足,一般签名都是这样实现,但是也有一些需要上传线上的点才能实现,这个时候就需要封装获取UIBezierPath上所有的,代码如下:

二、代码:

.h文件

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIBezierPath (AllPoints)

/** 获取贝塞曲线上的所有点 */
- (NSArray *)points;

@end

NS_ASSUME_NONNULL_END

.m文件

#import "UIBezierPath+AllPoints.h"

#define VALUE(_INDEX_) [NSValue valueWithCGPoint:points[_INDEX_]]

@implementation UIBezierPath (AllPoints)

void getPointsFromBezier(void *info,const CGPathElement *element){
    NSMutableArray *bezierPoints = (__bridge NSMutableArray *)info;
    CGPathElementType type = element->type;
    CGPoint *points = element->points;

    if (type != kCGPathElementCloseSubpath) {
        [bezierPoints addObject:VALUE(0)];
        if ((type != kCGPathElementAddLineToPoint) && (type != kCGPathElementMoveToPoint)) {
            [bezierPoints addObject:VALUE(1)];
        }
    }

    if (type == kCGPathElementAddCurveToPoint) {
        [bezierPoints addObject:VALUE(2)];
    }

}

//获取曲线的点,CGPoint数组
- (NSArray *)linesPoints {
    NSMutableArray *points = [NSMutableArray array];
    CGPathApply(self.CGPath, (__bridge void *)points, getPointsFromBezier);
    return points;
}

//数组转换,将CGPoint数组转换成,(x,y)字典数组
- (NSArray *)points
{
    NSArray *points = [self linesPoints];
    NSMutableArray *newPoints = [NSMutableArray new];
    for (NSInteger i = 0; i < points.count; i++) {
        CGPoint point = [points[i] CGPointValue];  //将元素转换成CGPoint
        NSMutableDictionary *dict = [NSMutableDictionary new];
        double x = point.x;
        double y = point.y;

        dict[@"x"] = @(x);
        dict[@"y"] = @(y);

        [newPoints addObject:dict];
    }

    return newPoints;
}

@end