IOS UI advanced 05 and iosui advanced

Source: Internet
Author: User

IOS UI advanced 05 and iosui advanced

  • Quartz2D
    • Quartz2D is a two-dimensional Drawing Engine.
      • The packaged function library is convenient for developers. That is to say, apple helped us encapsulate a set of graphic function libraries.
      • The same code written with Quartz2D can be run on both the iphone and mac, and can be developed across platforms.
      • Screenshots, cropping, and custom UI controls are commonly used during development. The value of Quartz2D in iOS development is custom UI controls.
      • Context can be obtained only in drawRect: method.
  • Quartz2D plotting
    • Custom view: You must override drawRect to draw a graph.
      • 1. It is called only when the drawRect view is to be displayed. It is called only after viewDidLoad, because the view is not displayed yet.
      • 2 Role: used for drawing
        • Draw a line
        • 1. Obtain the image Context
        • CG: indicates that this class is referenced by Ref in CoreGraphics framework.
        • To obtain the image context, first tap UIGraphics.
        • 2. Splicing path: This is generally used in development. It encapsulates many things and can help me draw some basic line segments, rectangles, circles, and so on.
        • Create the Bessert path
        • Start Point: moveToPoint
        • Endpoint: addLineToPoint
        • 3. Add the path to the context
      • CGPath conversion: You can directly convert the UIKit framework to CoreGraphics using CGPath.
        • 4> render the context to the view. The graphic context itself does not have the display function.
        • 5. Conclusion: first obtain the graphic context, then describe the path, add the path to the context, and render it to the view. The graphic context is equivalent to a memory cache zone, and the operation in the memory is the fastest, it is much faster than directly operating on the interface.
        • // When to call: This method will be called only when the current control is about to be displayed. // purpose: to draw the content, you only need to draw the content in a view in the future, you must draw-(void) drawRect :( CGRect) rect {// draw a curve // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. splicing path UIBezierPath * path = [UIBezierPath bezierPath]; // set the starting point [path moveToPoint: CGPointMake (10,125)]; // description curve [path addQuadCurveToPoint: CGPointMake (240,125) controlPoint: CGPointMake (125,240)]; [path addLineToPoint: CGPointMake (10,125)]; // 3. add the path to the context CGContextAddPath (ctx, path. CGPath); // set the drawing status before rendering. // set the color [[UIColor redColor] setStroke]; // set the width of the line segment CGContextSetLineWidth (ctx, 15 ); // set the top corner style CGContextSetLineCap (ctx, kCGLineCapRound) of a line segment; // set the connection style CGContextSetLineJoin (ctx, kCGLineJoinRound); // 4. rendering context CGContextStrokePath (ctx );}
      • Draw two unconnected lines
        • 1. When you draw the second image, reset the start point and draw the line. A path can contain multiple line segments.
        • 2. Create a new path and add it to the context. We recommend that you use this feature during development to easily control each line.
        • // Method for drawing two paths-(void) drawTwoLine {// 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. splicing path. Multiple line segments can be saved in one path: UIBezierPath * path = [UIBezierPath bezierPath]; [path moveToPoint: CGPointMake (10, 10)]; [path addLineToPoint: CGPointMake (20, 20)]; // 3. add the path to the context CGContextAddPath (ctx, path. CGPath); // a line corresponds to a path, as long as the drawn line is not connected, it is best to use a line corresponding to a path = [UIBezierPath bezierPath]; // concatenate another line. // the start point of the next line is the end point of the previous line by default. // set the start point of the second line. // [path moveToPoint: CGPointMake (20, 20)]; // if you want to draw an unconnected line, reset the starting point [path moveToPoint: CGPointMake (50, 50)]; [path addLineToPoint: CGPointMake (20,200)]; // 3. add the path to the context CGContextAddPath (ctx, path. CGPath); // 4. rendering context CGContextStrokePath (ctx );}
      • Arc
        • Analysis:
          • 1> an arc is a part of a circle. Therefore, an arc is generated only when a circle exists.
          • 2> do circles need a starting point? It is required to draw a line, and the circle is no different. -3> where is the start point? Right of center
          • 4> the starting angle, ending angle, direction, and angle must be radians when the arc is drawn.
          • // Draw an arc // Center center Center // radius: radius // startAngle start angle // endAngle: end angle // clockwise: Yes clockwise No counterclockwise CGPoint center = CGPointMake (self. bounds. size. width * 0.5, self. bounds. size. height * 0.5); UIBezierPath * path1 = [UIBezierPath bezierPathWithArcCenter: center radius: 100 startAngle: 0 endAngle: M_PI_2 clockwise: NO]; [path1 stroke];
      • Sector
        • // Sector UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter: center radius: 100 startAngle: 0 endAngle: M_PI_2 clockwise: YES]; [path addLineToPoint: center]; [path addLineToPoint: CGPointMake (self. bounds. size. height * 0.5 + 100, self. bounds. size. height * 0.5)]; // close the path: connect to the starting point [path closePath] from the end of the path; // set the fill color [[UIColor redColor] setFill]; // set the stroke color [[UIColor greenColor] setStroke]; // [path stroke]; // if the path is not closed, the path [path fill] is disabled by default.
      • Pie Chart
        • # Import "PieView. h "@ implementation PieView // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. -(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// redraw [self setNeedsDisplay];}-(void) drawRect :( CGRect) rect {// Drawing code NSArray * data = @ [@ 25, @ 25, @ 20, @ 30]; // The center of the CGPoint center = CGPointMake (self. bounds. size. width * 0.5, self. bounds. size. height * 0.5); // The angle CGFloat radius = self. bounds. size. width * 0.5; CGFloat startA = 0; CGFloat endA = 0; CGFloat angle = 0; for (NSNumber * num in data) {// draw a fan-shaped startA = endA; angle = [num intValue]/100.0 * M_PI * 2; endA = startA + angle; UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter: center radius: radius startAngle: startA endAngle: endA clockwise: YES]; [path addLineToPoint: center]; // set: set the stroke and fill color at the same time [[self randomColor] set]; [path fill];} // random color-(UIColor *) randomColor {CGFloat r = arc4random_uniform (256)/255.0; CGFloat g = arc4random_uniform (256)/255.0; CGFloat B = arc4random_uniform (256) /255.0; return [UIColor colorWithRed: r green: g blue: B alpha: 1];} @ end:

      • Draw words
        • -(Void) drawRect :( CGRect) rect {NSString * str = @ "hello! "; // Attributes: attribute // Add an attribute to a string, which can be rich text, color, font size, or hollow, shadow // use this attribute dictionary to add the attribute NSMutableDictionary * strAttr = [NSMutableDictionary dictionary] to the text; // key, value // how to locate the attribute key for setting text // describes the font strAttr [NSFontAttributeName] = [UIFont boldSystemFontOfSize: 50]; // set the stroke color and width strAttr [NSStrokeWidthAttributeName] = @ 1; strAttr [NSStrokeColorAttributeName] = [UIColor redColor]; NSShadow * shadow = [[NSShadow alloc] init]; shadow. shadowColor = [UIColor yellowColor]; shadow. shadowOffset = CGSizeMake (10, 10); shadow. shadowBlurRadius = 5; // shadow strAttr [NSShadowAttributeName] = shadow; // text color strAttr [plaintext] = [UIColor redColor]; [str drawAtPoint: CGPointZero withAttributes: strAttr];}:

           

    • Implement snow with Timer
        • # Import "SnowView. h "@ implementation SnowView-(void) awakeFromNib {// set the timer // [NSTimer scheduledTimerWithTimeInterval :. 1 target: self selector: @ selector (setNeedsDisplay) userInfo: nil repeats: YES]; // 0.1 setNeedsDisplay binds an ID, the drawRect method will be called only after the next refresh. // The refresh time of the 0.15 screen // timer // it will be called every time the screen is refreshed, the screen is refreshed 60 times a second. CADisplayLink * link = [CADisplayLink displayLinkWithTarget: self selector: @ selector (setNeedsDisplay)]; // as long as the timer is added to the main running cycle, it can automatically execute [link addToRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode]; // setNeedsDisplay: drawRect is not called immediately at the underlying layer, only one refresh identifier is bound to the current control. Each time the screen is refreshed, the control bound with the refresh (redrawing) identifier is rerefreshed (drawn) once, drawRect will be called to derepaint // if re-painting is required at intervals later, NSTimer is generally not used, and CADisplayLink is used, there will be no delay during refresh} // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. -(void) drawRect :( CGRect) rect {// Drawing code static CGFloat snowY = 0; UIImage * image = [UIImage imageNamed: @ "Snowflake"]; [image drawAtPoint: CGPointMake (0, snowY)]; snowY + = 10; if (snowY> rect. size. height) {snowY = 0 ;}}
          :

           

    • Graphical context status Stack
        • # Import "DrawView. h "@ implementation DrawView // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. -(void) drawRect :( CGRect) rect {// Drawing code // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. splicing path UIBezierPath * path = [UIBezierPath bezierPath]; [path moveToPoint: CGPointMake (10,125)]; [path addLineToPoint: CGPointMake (240,125)]; // 3. add the path to the context CGContextAddPath (ctx, path. CGPath); // Save the default status CGContextSaveGState (ctx) of the current context; // set the status [[UIColor redColor] set]; CGContextSetLineWidth (ctx, 20 ); // rendering context CGContextStrokePath (ctx); // create the Second path = [UIBezierPath bezierPath]; [path moveToPoint: CGPointMake (125, 10)]; [path addLineToPoint: CGPointMake (125,240)]; // Add to context CGContextAddPath (ctx, path. CGPath); // restore the context state. // retrieve the Saved state and overwrite the current state CGContextRestoreGState (ctx). // [[UIColor blackColor] set]; // CGContextSetLineWidth (ctx, 1); // 4. render context to view layer // before rendering, the system will view the context status and render CGContextStrokePath (ctx) according to the status;} @ end

      • Screenshot capture
        • # Import "ViewController. h "@ interface ViewController () @ property (nonatomic, weak) UIView * cover; @ property (nonatomic, assign) CGPoint oriP; @ property (weak, nonatomic) IBOutlet UIImageView * imageView; @ property (weak, nonatomic) IBOutlet UIView * view1; @ end @ implementation ViewController-(UIView *) cover {if (_ cover = nil) {UIView * view = [[UIView alloc] init]; view. backgroundColor = [UIColor blackColor]; view. alpha = 0.5; _ cover = view; [self. view addSubview: view];} return _ cover;}-(IBAction) pan :( UIPanGestureRecognizer *) sender {// obtain the current touch CGPoint curP = [sender locationInView: _ imageView]; if (sender. state = UIGestureRecognizerStateBegan) {// record location _ oriP = curP;} // calculate the frame CGFloat w = curP. x-_ oriP. x; CGFloat h = curP. y-_ oriP. y; self. cover. frame = CGRectMake (_ oriP. x, _ oriP. y, w, h); if (sender. state = UIGestureRecognizerStateEnded) {// raise your finger // crop the image to generate a new image // enable the bitmap context uigraphicsbeginimagecontextwitexceptions (_ imageView. bounds. size, NO, 0); // you can specify UIBezierPath * path = [UIBezierPath bezierPathWithRect: self. cover. frame]; [path addClip]; // draw an image [_ imageView. layer renderInContext: UIGraphicsGetCurrentContext ()]; // generate image UIImage * image = UIGraphicsGetImageFromCurrentImageContext (); // disable context UIGraphicsEndImageContext (); _ imageView. image = image; [self. cover removeFromSuperview] ;}}@ end: Before screenshots
          : After screenshots
           
      • Image Erasure
        • # Import "ViewController. h "@ interface ViewController () @ end @ implementation ViewController // drag the user's finger on the image. you will call the-(IBAction) pan :( UIPanGestureRecognizer *) sender {// when dragging, erase a part of the image // obtain the finger's touch point CGPoint curP = [sender locationInView: sender. view]; // calculates the erased frame CGFloat wh = 30; CGFloat x = curP. x-wh * 0.5; CGFloat y = curP. y-wh * 0.5; CGRect frame = CGRectMake (x, y, wh, wh); // enable the bitmap context uigraphicsbeginimagecontextwitexceptions (sender. view. bounds. size, NO, 0); // obtain the current context CGContextRef ctx = UIGraphicsGetCurrentContext (); // render the content on the control to the context [sender. view. layer renderInContext: ctx]; // clear CGContextClearRect (ctx, frame) in a part of the context; // generate a new image UIImage * image = UIGraphicsGetImageFromCurrentImageContext (); // disable the context UIGraphicsEndImageContext (); // re-display it to UIImageView * imageV = (UIImageView *) sender. view; imageV. image = image;} @ end: Before Erasure: After Erasure:

           

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.