1. 程式人生 > >iOS手寫簽名生成圖片

iOS手寫簽名生成圖片

最近公司業務有一個需求,使用者認證時需要手動簽名,客戶端需要將使用者的簽名生成圖片上傳給伺服器。於是利用貝賽爾曲線研究了一下手動簽名,和大家分享一下。
Demo下載地址:https://github.com/TechAlleyBoy/SignDemo

效果圖
這裡寫圖片描述
生成的圖片,這裡製作的是透明的簽名
這裡寫圖片描述

一:繪製操作,主要利用的是貝賽爾曲線
注意:在呼叫setNeedsDisplay方法後,會在呼叫drawRect

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if
(self) { self.backgroundColor = [UIColor clearColor]; [self setMultipleTouchEnabled:NO]; self.beizerPath = [UIBezierPath bezierPath]; [self.beizerPath setLineWidth:2]; } return self; } #pragma mark - 繪圖操作 - (void)drawRect:(CGRect)rect{ //設定簽名的顏色 UIColor
*strokeColor = [UIColor redColor]; [strokeColor setStroke]; //簽名的路徑繪製 [self.beizerPath stroke]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ self.control = 0; UITouch *touch = [touches anyObject]; points[0] = [touch locationInView:self]; CGPoint
startPoint = points[0]; CGPoint endPoint = CGPointMake(startPoint.x + 1.5, startPoint.y + 2); [self.beizerPath moveToPoint:startPoint]; [self.beizerPath addLineToPoint:endPoint]; } - (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); //設定畫筆起始點 [self.beizerPath moveToPoint:points[0]]; //endPoint終點 controlPoint1、controlPoint2控制點 [self.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; } }

二:清除簽名
注意:如何需要透明度的圖片時,首先view是透明的,然後一定生成png的圖片,否則不是黑色背景就是白色背景。

#pragma mark - 清除簽名
- (void)clearSignature{
    [self.beizerPath removeAllPoints];
    [self setNeedsDisplay];
}

三:獲取圖片

#pragma mark - 獲取圖片
- (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/IMAGE.PNG", NSHomeDirectory()];

    //用png是透明的
    [UIImagePNGRepresentation(signatureImage) writeToFile: path atomically:YES];
    return signatureImage;
}