Skip to content

Instantly share code, notes, and snippets.

@ZackMcBride
Created October 16, 2013 20:08
Show Gist options
  • Save ZackMcBride/7013943 to your computer and use it in GitHub Desktop.
Save ZackMcBride/7013943 to your computer and use it in GitHub Desktop.
Simple signature capture functionality for iOS. Comes with methods to output as either string of coords or image.
- (void)pan:(UIPanGestureRecognizer *)pan {
CGPoint currentPoint = [pan locationInView:self];
CGPoint midPoint = midpoint(previousPoint, currentPoint);
if (pan.state == UIGestureRecognizerStateBegan) {
[path moveToPoint:currentPoint];
currentPath = [NSMutableArray arrayWithObject:[NSValue valueWithCGPoint:currentPoint]];
} else if (pan.state == UIGestureRecognizerStateChanged) {
[path addQuadCurveToPoint:midPoint controlPoint:previousPoint];
[currentPath addObject:[NSValue valueWithCGPoint:midPoint]];
[currentPath addObject:[NSValue valueWithCGPoint:currentPoint]];
} else if (pan.state == UIGestureRecognizerStateEnded) {
if (currentPath != nil) {
[paths addObject: currentPath];
hasContent = YES;
}
}
previousPoint = currentPoint;
[self setNeedsDisplay];
}
- (void)clear {
path = [UIBezierPath bezierPath];
paths = [[NSMutableArray alloc] init];
[self setNeedsDisplay];
}
static CGPoint midpoint(CGPoint p0, CGPoint p1) {
return (CGPoint) {
(p0.x + p1.x) / 2.0,
(p0.y + p1.y) / 2.0
};
}
- (void)drawRect:(CGRect)rect
{
[[UIColor blackColor] setStroke];
[path stroke];
}
- (UIImage*)getImageRepresentation {
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
- (NSString*)getStringRepresentation {
NSString *retString = @"";
for (NSArray *pathArray in paths) {
bool firstPoint = YES;
for(NSValue *pointValue in pathArray){
CGPoint point = [pointValue CGPointValue];
if (firstPoint) {
firstPoint = NO;
retString = [retString stringByAppendingFormat:
@"s:%f,%f;", point.x, point.y];
} else {
retString = [retString stringByAppendingFormat:
@"p:%f,%f;", point.x, point.y];
}
}
}
return retString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment