How to draw signature with lines on iPhone screen?
-
22-08-2019 - |
Question
I want to let user draw a signature on iPhone screen, so I add a subclass of UIView and add some code to its 'touchesMoved' method.
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
firstTouch = [touch locationInView:self];
CGSize mySize = CGSizeMake(5, 5);
UIGraphicsBeginImageContext(mySize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
CGContextAddRect(ctx, CGRectMake(0, 0, 5, 5));
CGContextFillPath(ctx);
UIImage *redRect = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *redRectView = [[UIImageView alloc] initWithImage:redRect];
redRectView.center = CGPointMake(firstTouch.x, firstTouch.y);
[self addSubview:redRectView];
}
I'm drawing it with small rectangles and it turns out to be dot by dot. As it is too ugly, I want to draw the signature with lines. But how to distinguish firstTouch and lastTouch? If I only use 'touchesMoved' method, I can only get one touch point.
Solution
As per the UIResponder Class Reference, you will also need to implement
– touchesBegan:withEvent:
and
– touchesEnded:withEvent:
.
After you implement these methods, you should be able to get enough data to implement a pathing bezier curve or other suitable solution.
[edit] A perhaps better solution would to be to obtain the touches directly from the UIEvent
object once your controller receives a
– touchesMoved:withEvent:
notification. Also, the GLPaint sample code may also prove helpful.
OTHER TIPS
As the GLPaint sample code may be too complicated for beginners, I find this tutorial. It is simple to learn for most beginners.
Keep in mind that a signature written with one's finger is going to be different than one written with a writing instrument. You may want to re-think what you're using the signature for, and whether it's as binding as you need it to be.