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;   //是否已經(jīng)簽了名
@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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末淹冰,一起剝皮案震驚了整個濱河市堆巧,隨后出現(xiàn)的幾起案子肠套,更是在濱河造成了極大的恐慌,老刑警劉巖梳侨,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尺上,死亡現(xiàn)場離奇詭異材蛛,居然都是意外死亡,警方通過查閱死者的電腦和手機尖昏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門仰税,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抽诉,你說我怎么就攤上這事陨簇。” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵河绽,是天一觀的道長己单。 經(jīng)常有香客問我,道長耙饰,這世上最難降的妖魔是什么纹笼? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮苟跪,結(jié)果婚禮上廷痘,老公的妹妹穿的比我還像新娘。我一直安慰自己件已,他們只是感情好笋额,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著篷扩,像睡著了一般兄猩。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鉴未,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天枢冤,我揣著相機與錄音,去河邊找鬼铜秆。 笑死淹真,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的连茧。 我是一名探鬼主播趟咆,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼梅屉!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起鳞贷,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤坯汤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后搀愧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體惰聂,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年咱筛,在試婚紗的時候發(fā)現(xiàn)自己被綠了搓幌。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡迅箩,死狀恐怖溉愁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情饲趋,我是刑警寧澤拐揭,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布撤蟆,位于F島的核電站,受9級特大地震影響堂污,放射性物質(zhì)發(fā)生泄漏家肯。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一盟猖、第九天 我趴在偏房一處隱蔽的房頂上張望讨衣。 院中可真熱鬧,春花似錦式镐、人聲如沸反镇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽愿险。三九已至,卻和暖如春价说,著一層夾襖步出監(jiān)牢的瞬間辆亏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工鳖目, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留扮叨,地道東北人。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓领迈,卻偏偏與公主長得像彻磁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子狸捅,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355