iOS 手写签名

手写签名

.h

// 手写签名视图

#import <UIKit/UIKit.h>

@protocol HandwritenSignatureDelegate <NSObject>

@optional
- (void)handwritenSignViewDidFinish:(UIImage*)signedImage;

@optional
- (void)changeStatusBarState:(BOOL)hidden;
@end


#pragma mark - HandwritenSignatureView
@interface HandwritenSignatureView : UIView

@property(nonatomic, weak) id<HandwritenSignatureDelegate> delegate;

/**
 初始化方法
 
 @param frame frame
 @param lineWidth 签名时线条宽度,默认为2.0,最大为20
 */
- (id)initWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth;

- (void)startHandwriteSign; //初始化签名页面
- (void)clearSignature;     //清除签名

@end

.m

#import "HandwritenSignatureView.h"

#define ColorFromRGB(rgb) [UIColor colorWithRed:((float) ((rgb & 0xFF0000) >> 16)) / 255.0 \
                                          green:((float) ((rgb & 0xFF00) >> 8)) / 255.0    \
                                           blue:((float) (rgb & 0xFF)) / 255.0             \
                                          alpha:1.0]
#define kBgColorWhite           0xFFFFFF
#define kFontColorImp33         0x333333    //浅黑色
#define kNewSepLineColor        0xD7D7D7    //分割线颜色(5.0之后的样式)
#define kBgColorDisableGray     0xCCCCCC    //灰色不可点击
#define kSystemFont18       [UIFont fontWithName:@"Helvetica" size:18]

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#pragma mark -
#pragma mark - CanvasView
@interface CanvasView : UIView
{
    UIBezierPath *path; //签名笔迹
    CGPoint points[5];  //签名时移动的轨迹记录
    uint pointIndex;    //
    
    BOOL _isSigned;     //是否签了名
}
@property(nonatomic, assign) CGFloat lineWidth;  //签名线条宽度

- (id)initWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth;

- (void)clearCanvas;  //清空画布
- (UIImage*)getSignatureImage; //获取签名的图片
- (BOOL)isSigned;   //是否已经签了名
@end


@implementation CanvasView
- (id)initWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth
{
    if( (self = [super initWithFrame:frame]) ){
        _lineWidth = (lineWidth <= CGFLOAT_MIN || lineWidth > 20.0) ? 2.0 :lineWidth;
        [self initContent];
    }

    return self;
}

- (void)drawRect:(CGRect)rect {
    //    [signedImage drawInRect:rect];
    [path stroke];
}

#pragma mark - public method
- (void)clearCanvas
{
    _isSigned = NO;
    pointIndex = 0;
    bzero(points, sizeof(points));
    [path removeAllPoints];
    [self setNeedsDisplay];
}

- (UIImage*)getSignatureImage
{
    UIImage *image = nil;
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0);
    if( !image ){
        UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds];
        [[UIColor whiteColor] setFill];
        [rectpath fill];
    }
    [image drawAtPoint:CGPointZero];
    [[UIColor blackColor] setStroke];
    [path stroke];
    image = UIGraphicsGetImageFromCurrentImageContext(); //UIGraphicsgetSignatureImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    
    return image;
}

- (BOOL)isSigned
{
    return _isSigned;
}

#pragma mark - touch events
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    pointIndex = 0;
    UITouch *touch = [touches anyObject];
    points[0] = [touch locationInView:self];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    pointIndex++;
    points[pointIndex] = p;
    if(pointIndex == 4)
    {
        points[3] = CGPointMake( (points[2].x + points[4].x) / 2.0, (points[2].y + points[4].y)/2.0 );
        
        [path moveToPoint:points[0]];
        [path addCurveToPoint:points[3] controlPoint1:points[1] controlPoint2:points[2]];
        
        [self setNeedsDisplay];
        points[0] = points[3];
        points[1] = points[4];
        pointIndex = 1;
    }
    
    if(!_isSigned)
        _isSigned = YES;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //    [self getSignatureImage];
    //    [path removeAllPoints];
    pointIndex = 0;
    [self setNeedsDisplay];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

#pragma mark - init
- (void)initContent
{
    _isSigned = NO;
    self.backgroundColor = [UIColor whiteColor];
    [self setMultipleTouchEnabled:NO];
    path = [UIBezierPath bezierPath];
    [path setLineWidth:_lineWidth];
}

@end

#pragma mark -
#pragma mark - HandwritenSignatureView
@interface HandwritenSignatureView ()

@property(nonatomic, strong) CanvasView *drawView;
@property(nonatomic, strong) UIView *btnContainer;
@property(nonatomic, strong) UIButton *clearBtn;
@property(nonatomic, strong) UIButton *confirmBtn;
@property(nonatomic, strong) UILabel *titleLabel;
@property(nonatomic, strong) UIView *sep;
@end

@implementation HandwritenSignatureView

- (id)initWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth
{
    if( (self = [super initWithFrame:frame]) )
    {
        [self setLeftOrientation];
        [self initContentWithLineWidth:lineWidth];
    }
    
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    _btnContainer.frame = CGRectMake(0.0, 0.0, self.frame.size.height, 69.0);
    _clearBtn.frame = CGRectMake(20.0, 15.0, 100.0, 40.0);
    _titleLabel.frame = CGRectMake( (self.frame.size.height - 315.0)/2.0, (_btnContainer.frame.size.height - 22.0) / 2.0, 315.0 , 22.0);
    _confirmBtn.frame = CGRectMake( self.frame.size.height - 100.0 - 15.0, 15.0, 100.0, 40.0);
    _sep.frame = CGRectMake(0.0, _btnContainer.frame.size.height - 0.5, self.frame.size.height, 0.5);
    
    _drawView.frame = CGRectMake(0.0, _btnContainer.frame.size.height, self.frame.size.height, self.frame.size.width - _btnContainer.frame.size.height) ;
    
}

#pragma mark -
- (void)startHandwriteSign
{
    [self setLeftOrientation];
    if(self.delegate && [self.delegate respondsToSelector:@selector(changeStatusBarState:)]){
        [self.delegate changeStatusBarState:YES];
    }
}

- (void)clearSignature
{
    [_drawView clearCanvas];
}

#pragma mark - private method
- (void)initContentWithLineWidth:(CGFloat)lineWidth
{
    self.backgroundColor = ColorFromRGB(kBgColorWhite);
    
    _btnContainer = [self viewWithFrame:CGRectZero bgColor:ColorFromRGB(kBgColorWhite)];
    [self addSubview:_btnContainer];
    
    _clearBtn = [self buttonWithFrame:CGRectZero title:@"重签" action:@selector(clearAction:)];
    [_btnContainer addSubview:_clearBtn];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLabel.text = @"用正楷字从左往右签署身份证上的姓名";
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = kSystemFont18;
    _titleLabel.textColor = ColorFromRGB(kFontColorImp33);
    [_btnContainer addSubview:_titleLabel];
    
    _confirmBtn = [self buttonWithFrame:CGRectZero title:@"完成" action:@selector(confirmAction:)];
    [_btnContainer addSubview:_confirmBtn];
    
    _sep = [self viewWithFrame:CGRectZero bgColor:ColorFromRGB(kNewSepLineColor)];
    [_btnContainer addSubview:_sep];
    
    _drawView = [[CanvasView alloc] initWithFrame:CGRectZero lineWidth:lineWidth];
    [self addSubview:_drawView];
}

#pragma mark - actions
- (void)clearAction:(id)sender
{
    [_drawView clearCanvas];
}

- (void)confirmAction:(id)sender
{
    __weak typeof(self) this = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if(this.delegate && [this.delegate respondsToSelector:@selector(changeStatusBarState:)]){
            [this.delegate changeStatusBarState:NO];
        }
        
        UIImage *image = nil;
        if( [this.drawView isSigned] )
            image = [this.drawView getSignatureImage];
        
        if( this.delegate && [this.delegate respondsToSelector:@selector(handwritenSignViewDidFinish:)] ){
            [this.delegate handwritenSignViewDidFinish:image];
        }

        [this removeFromSuperview];
    });
}

#pragma mark -
-(void)setLeftOrientation
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2);//CGAffineTransformMakeRotation(M_PI_2);
        self.bounds = CGRectMake(0.0, 0.0, SCREEN_HEIGHT, SCREEN_WIDTH);
        [self setNeedsLayout];
    });
}

#pragma mark - getter / setter
- (UIButton*)buttonWithFrame:(CGRect)frame title:(NSString*)title action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = kSystemFont18;
    button.layer.borderWidth = 0.5;
    button.layer.borderColor = ColorFromRGB(kBgColorDisableGray).CGColor;
    button.layer.cornerRadius = 20.0;
    button.layer.masksToBounds = YES;
    [button setTitleColor:ColorFromRGB(kFontColorImp33) forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];

    return button;
}

- (UIView*)viewWithFrame:(CGRect)frame bgColor:(UIColor*)bgColor
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = bgColor;
    return view;
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354