The implementation of Quartz2D drawing board in IOS () UI of catcat learning, iosquartz2d
CAT/CAT sharing, must be excellent
For Original Articles, please reprint them. Reprinted Please note: Yan Nai-yu's blog
Http://blog.csdn.net/u013357243? Viewmode = contents
Source code: http://blog.csdn.net/u013357243/article/details/45533403
Effect:
Implementation process:
First, use storyboard to build the interface. There is nothing to say.
Then, we should pay attention to the function. Here we use touch events to draw images with Quartz2D paths.
The idea is to put the path in the array.
@property (nonatomic, strong) NSMutableArray *paths;
Note that if the C language is used
CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 20, 20); CGPathAddLineToPoint(path, NULL, 100, 100);
The image cannot be placed in the oc array. Therefore, UIBezierPath is used to create a path object.
UIBezierPath *path = [UIBezierPath bezierPath];
Then put the path in the array and render it.
Note: At the beginning, I didn't call the re-painting method, and then there was no tragedy. Depressed for a long time.
Redraw:
Call the drawRect method to return to the view
[self setNeedsDisplay];
Code Implementation
Start to touch:
// Start to touch-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// 1. obtain the UITouch object UITouch * touch = [touches anyObject]; // 2. obtain the position of the finger touch through the UITouch object CGPoint startPoint = [touch locationInView: touch. view]; // 3. when you press your finger, create a path UIBezierPath * path = [UIBezierPath bezierPath]; // 3.1 set the path attributes [path setLineJoinStyle: kCGLineJoinRound]; [path setLineCapStyle: Custom]; [path setLineWidth: 10]; // 4. set the starting point of the current path [path moveToPoint: startPoint]; // 5. add the path to the array [self. paths addObject: path];}
Mobile:
// Mobile-(void) touchesMoved :( NSSet *) touches withEvent :( UIEvent *) event {// 1. obtain the UITouch object UITouch * touch = [touches anyObject]; // 2. obtain the position of the finger touch through the UITouch object CGPoint movePoint = [touch locationInView: touch. view]; // 3. retrieve the current path UIBezierPath * currentPaht = [self. paths lastObject]; // 4. set the end point of the current path [currentPaht addLineToPoint: movePoint]; // 6. call the drawRect method to return to the view [self setNeedsDisplay];}
Rollback and screen clearing methods:
- (void)clearView{ [self.paths removeAllObjects]; [self setNeedsDisplay];}- (void)backView{ [self.paths removeLastObject]; [self setNeedsDisplay];}
The wire draw method is implemented by traversing the UIBezierPath object in the array.
// Draw line-(void) drawRect :( CGRect) rect {[UIColor redColor] set]; // draw all line segments in the edge array for (UIBezierPath * path in self. paths) {[path stroke] ;}}