IOS simple canvas implementation, ios canvas

Source: Internet
Author: User

IOS simple canvas implementation, ios canvas

 

 

Design Requirements

1. Set the size and color of the paint brush.

2. Clear screen, undo, eraser, and photo import Functions

3. Save the painted image to the album.

 

Implementation

1. Paint Brush implementation. We can create UIBezierPath by listening to users' translation gestures to draw lines.

2. The Undo function. Let's look at the Undo function first. We will think of adding each stroke of the user to the array with an array queue, then, you only need to pop the last stroke to be added and re-draw it.

3. The screen clearing function is simple. You only need to clear the array mentioned above and redraw it.

4. Import the photo function. You can use the system's UIImagePickerController to select a photo to obtain the UIImage, and then draw the UIImage to the screen.

5. Save to the album function. You can use UIGraphicsGetImageFromCurrentImageContext to obtain the context of the current image, obtain the UIImage of the screen, and then write the image to the album through UIImageWriteToSavedPhotosAlbum.

 

Code Implementation

1. Draw an interface first

2. Because UIBezierPath is used to draw a line and the color must be configurable, but UIBezierPath does not have a color attribute, we need to expand it here, create a subclass DrawPath that inherits from UIBezierPath

//// DrawPath. h // canvas /// Created by xgao on 16/4/13. // Copyright©2016 xgao. All rights reserved. // # import <UIKit/UIKit. h> @ interface DrawPath: UIBezierPath
// Paint brush color @ property (nonatomic, retain) UIColor * pathColor; @ end

This subclass only needs to extend one attribute, that is, pathColor is used to save the color of the paint brush.

//// DrawPath. m // canvas /// Created by xgao on 16/4/13. // Copyright©2016 xgao. All rights reserved. // # import "DrawPath. h" @ implementation DrawPath @ end

Other functions are not required in DrawPath. m.

3. We encapsulate the implementation of the canvas function and create a DrawView subclass inherited from UIView.

//// DrawView. h // canvas /// Created by xgao on 16/4/13. // Copyright©Xgao. all rights reserved. // # import <UIKit/UIKit. h> @ interface DrawView: UIView // width of the draw Line @ property (nonatomic, assign) CGFloat lineWidth; // line color @ property (nonatomic, retain) UIColor * pathColor; // load the background image @ property (nonatomic, strong) UIImage * image; // clear the screen-(void) clear; // undo-(void) undo; // eraser-(void) eraser; // save-(void) save; @ end
//// DrawView. m // canvas /// Created by xgao on 16/4/13. // Copyright©Xgao. all rights reserved. // # import "DrawView. h "# import" DrawPath. h "@ interface DrawView () @ property (nonatomic, strong) DrawPath * path; // line array @ property (nonatomic, strong) NSMutableArray * paths; @ end @ implementation DrawView-(void) awakeFromNib {[self setUp];}-(instancetype) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {[self setUp];} return self;} // re-paint UI-(void) drawRect :( CGRect) rect {for (DrawPath * path in self. paths) {if ([path isKindOfClass: [UIImage class]) {// picture UIImage * image = (UIImage *) path; [image drawInRect: rect];} else {// draw a line // set the paint brush color [path. pathColor set]; // draw [path stroke] ;}}// lazy load Attribute-(NSMutableArray *) paths {if (_ paths = nil) {_ paths = [NSMutableArray array];} return _ paths;} // rewrite the image Attribute-(void) setImage :( UIImage *) image {_ image = image; // Add the image to the line array [self. paths addObject: image]; [self setNeedsDisplay];} # pragma mark-Init // initialization-(void) setUp {// Add the translation gesture ** panGes = [[UIPanGestureRecognizer alloc] initWithTarget: self action: @ selector (panGes :)]; [self addGestureRecognizer: panGes]; // default value self. lineWidth = 1; self. pathColor = [UIColor blackColor] ;}# pragma mark-Event // translation Event-(void) panGes :( UIPanGestureRecognizer *) ges {// obtain the current vertex CGPoint curPoint = [locges ationinview: self]; if (ges. state = UIGestureRecognizerStateBegan) {// start to move. // create the beiser curve _ path = [[DrawPath alloc] init]; // set the line width _ path. lineWidth = _ lineWidth; // default line color _ path. pathColor = _ pathColor; // set the starting point [_ path moveToPoint: curPoint]; [self. paths addObject: _ path];} // link [_ path addLineToPoint: curPoint]; // redraw [self setNeedsDisplay];} # pragma mark-Method // clear screen-(void) clear {[self. paths removeAllObjects]; [self setNeedsDisplay];} // undo-(void) undo {[self. paths removeLastObject]; [self setNeedsDisplay];} // eraser-(void) eraser {self. pathColor = [UIColor whiteColor]; [self setNeedsDisplay];} // save-(void) save {// ---- operation // enable context uigraphicsbeginimagecontextwitexceptions (self. frame. size, NO, 0); // obtain the current context CGContextRef context = UIGraphicsGetCurrentContext (); // render the layer to the context [self. layer renderInContext: context]; // obtain the image UIImage * image = watermark () from the context; // disable the context UIGraphicsEndImageContext (); // ---- Save the image UIImageWriteToSavedPhotosAlbum (image, self, @ selector (image: didFinishSavingWithError: contextInfo :), nil);} // Method for saving the image. You must write this method body and cannot save the image.-(void) image :( UIImage *) image success :( NSError *) error contextInfo :( void *) contextInfo {// The prompt is UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "saved successfully" message: nil delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alert show] ;}@ end

 

4. The next step is to use the canvas class, and directly add the code.

/// ViewController. m // canvas /// Created by xgao on 16/4/13. // Copyright©Xgao. all rights reserved. // # import "ViewController. h "# import" DrawView. h "@ interface ViewController () <UIImagePickerControllerDelegate, drawing> // canvas @ property (weak, nonatomic) IBOutlet DrawView * drawView; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad] ;}# pragma mark-Event // line width variation-(IBAction) lineWidthChange :( UISlider *) sender {_ drawView. lineWidth = sender. value;} // line color change-(IBAction) pathColorChange :( UIButton *) sender {_ drawView. pathColor = sender. backgroundColor;} // clear screen-(IBAction) clearAction :( id) sender {[_ drawView clear];} // Undo-(IBAction) undoAction :( id) sender {[_ drawView undo];} // IBAction eraserAction :( id) sender {[_ drawView eraser];} // photo-(IBAction) pickerPhotoAction :( id) sender {// select the Controller UIImagePickerController * picVC = [[UIImagePickerController alloc] init]; // picVC for the photo source. sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // delegate picVC. delegate = self; [self presentViewController: picVC animated: YES completion: nil];} // save-(IBAction) saveAction :( id) sender {[_ drawView save];} # pragma mark-extract-(void) imagePickerController :( UIImagePickerController *) picker didFinishPickingImage :( UIImage *) image editingInfo :( nullable NSDictionary <NSString *, id> *) editingInfo {// set image _ drawView. image = image; // close the window [self dismissViewControllerAnimated: YES completion: nil];} @ end

 

It's almost the same here. I have put the basic idea and specific code for implementing this small function. If you have any questions, please leave a message ~~

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.