(IOS)签名Demo

思路是将每一次按下屏幕的touch move时的点存到一个数组里,即一个数组相当于一个笔画;再将该代表笔画的数组保存到一个大数组中,每组每次touch的移动都历遍大数组和笔画数组,将点于点之间连接起来。

#import <UIKit/UIKit.h>
@interface BIDDrawView : UIView
{
    NSMutableArray *allPoints;
}

@end

 

#import "BIDDrawView.h"

@implementation BIDDrawView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        allPoints=[[NSMutableArray alloc] init];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame=CGRectMake(10, 30, 100, 30);
        [btn addTarget:self action:@selector(undo:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
    return self;
}

-(void)undo:(UIButton *)sender
{
    if (allPoints.count>0) {   // 如果撤销有问题需要把该判断移除
        [allPoints removeLastObject];
        [self setNeedsDisplay];
    }
}

- (void)drawRect:(CGRect)rect
{
    if (allPoints.count == 0) {
        return;
    }
    
    CGContextRef ctx=UIGraphicsGetCurrentContext();  //获取画板,或者说获取画图上下文。
    CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor); //设置画笔颜色。
    CGContextSetLineWidth(ctx, 1.5); //设置线条宽度。
    
    for (NSMutableArray *points in allPoints) {
        for (int i=0;i<points.count-1;i++) {
            if (points.count==0) {
                break;
            }
            NSValue *sValue = [points objectAtIndex:i];
            CGPoint sPoint=[sValue CGPointValue];
            
            NSValue *eValue = [points objectAtIndex:i+1];
            CGPoint ePoint=[eValue CGPointValue];
            
            CGContextMoveToPoint(ctx, sPoint.x, sPoint.y); //前往起点。
            CGContextAddLineToPoint(ctx, ePoint.x, ePoint.y); //由起点加线到终点。
            
            CGContextStrokePath(ctx);
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSMutableArray *points = [NSMutableArray array];
    [allPoints addObject:points];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    NSValue *v = [NSValue valueWithCGPoint:p]; //CGPoint 转为 对象
    NSMutableArray *points = [allPoints lastObject];
    [points addObject:v];
    //驱动画笔(drawRect方法)
    [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {}
@end

 

效果:

posted @ 2013-08-01 12:37  MingFung_Liu  阅读(474)  评论(0编辑  收藏  举报