这个画线功能主要是为了辅助在iOS中支持手势锁屏的功能,哪位知道有现成的GestureLock项目的,求分享。
2.
3. @property (nonatomic, strong) UIImageView *imageView;
4.
5. @property (nonatomic, assign) CGPoint lineStartPoint;
6. @property (nonatomic, assign) CGPoint lineEndPoint;
7.
8. @end
要画线,需要有画板imageView,还有线的起始点、终点。
通过Cocoa Touch支持的交互特性,我们可以跟踪用户手指点击和移动:
1. #pragma mark - Trace Touch Point
2.
3. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
4. {
5. CGPoint touchPoint;
6.
7. UITouch *touch = [touches anyObject];
8. if (touch) {
9. touchPoint = [touch locationInView:self.imageView];
10. "touchesBegan : %f, %f\n", touchPoint.x, touchPoint.y);
11.
12. self.lineStartPoint = touchPoint;
13. }
14. }
15.
16. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
17. {
18. CGPoint touchPoint;
19.
20. UITouch *touch = [touches anyObject];
21. if (touch) {
22. touchPoint = [touch locationInView:self.imageView];
23. "touchesMoved : %f, %f\n", touchPoint.x, touchPoint.y);
24.
25. self.lineEndPoint = touchPoint;
26. self.imageView.image = [self drawLineWithColor:[UIColor yellowColor] width:10.0f startPoint:self.lineStartPoint endPoint:self.lineEndPoint];
27. }
28. }
29.
30. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
31. {
32. ;
33. }
最后就是基础的画线功能:
1. #pragma mark - Draw Line
2.
3. - (UIImage *)drawLineWithColor:(UIColor *)color width:(CGFloat)width startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint
4. {
5. UIImage *image = nil;
6.
7. UIGraphicsBeginImageContext(self.imageView.frame.size);
8.
9. CGContextRef context = UIGraphicsGetCurrentContext();
10.
11. CGContextSetLineWidth(context, width);
12. CGContextSetStrokeColorWithColor(context, [color CGColor]);
13.
14. CGContextMoveToPoint(context, startPoint.x, startPoint.y);
15. CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
16.
17. CGContextStrokePath(context);
18.
19. image = UIGraphicsGetImageFromCurrentImageContext();
20.
21. UIGraphicsEndImageContext();
22.
23. return image;
24. }
这样,就可以根据手指移动来绘制线条了。
这个功能可以做一些趣味App,或者我的目的:手势锁屏和解锁。
如下是简单效果图: