手写签名Signature

最近很久没更新了,没办法一堆的需求刚刚忙完就接着一堆的需求,内心是奔溃的,UI妹子说要疯了是不是考虑转行了?‍♀️
一个需求线上签名,需要对对应的合同让用户进行签名,为了方便就有了线上签名的需求了。
看了下网上的签名都是大同小异,主要是计算像素点的问题,因为方法的不同写出来的效果也有点区别,但是大同小异哈都是使用UIBezierPath(这边整理了两个方法demo)。

方法一

使用五个点来计算像素点,通过五个点计算点与点之间的距离以及位置,让每个点连接起来比较自然,具体做法如下:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    
    CGPoint touchPoint = [touch locationInView:self];
    
    _control ++;
    
    points[_control] = touchPoint;
    
    if (_control == 4){
        points[3] = CGPointMake((points[2].x + points[4].x)/2.0, (points[2].y + points[4].y)/2.0);
        
        //设置画笔起始点
        [_beizerPath moveToPoint:points[0]];
        
        //endPoint终点 controlPoint1、controlPoint2控制点
        [_beizerPath addCurveToPoint:points[3] controlPoint1:points[1] controlPoint2:points[2]];
        
        //setNeedsDisplay会自动调用drawRect方法,这样可以拿到UIGraphicsGetCurrentContext,就可以画画了
        [self setNeedsDisplay];
        
        points[0] = points[3];
        
        points[1] = points[4];
        
        _control = 1;
    }
}
手写签名Signature_第1张图片
方法一效果.gif

方法二

通过前后两个点来计算处理点与点之间的距离

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint currentPoint = [[touches anyObject] locationInView:self];
    
    CGPoint midPoint = midpoint(_previousPoint, currentPoint);
    
    [_beizerPath addQuadCurveToPoint:midPoint controlPoint:_previousPoint];
    
    _previousPoint = currentPoint;
    
    [self setNeedsDisplay];
}

计算点之间的方法:

static CGPoint midpoint(CGPoint p0, CGPoint p1) {
    return (CGPoint) {
        (p0.x + p1.x) / 2.0,
        (p0.y + p1.y) / 2.0
    };
}
手写签名Signature_第2张图片
方法二效果.gif

具体的后面会有demo。

清除签名与获取签名图片

清除签名

#pragma mark -- 清除签名
- (void)clearSignature
{
    [_beizerPath removeAllPoints];
    
    [self setNeedsDisplay];
}

获取签名图片

- (UIImage *)getSignatureImage
{
    //设置为NO,UIView是透明这里的图片就是透明的
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *signatureImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    NSString* docDir = [NSString stringWithFormat:@"%@/Documents/Image", NSHomeDirectory()];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:docDir withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *path = [NSString stringWithFormat:@"%@/Documents/Image/Signature.PNG", NSHomeDirectory()];
    
    //用png是透明的
    [UIImagePNGRepresentation(signatureImage) writeToFile: path atomically:YES];
    
    return signatureImage;
}

就这些吧,写着充当笔记哈,下次使用的时候提供一个方便性。当然,不能耍流氓不上demo。

你可能感兴趣的:(手写签名Signature)