Graph in iOS development-Quartz2D-

Source: Internet
Author: User
Tags crop image

Graph in iOS development-Quartz2D-

 

What is Quartz2D?

Quartz 2D is a two-dimensional Drawing Engine that supports both iOS and Mac systems.

Function
Quartz 2D can complete the work of drawing graphics: line, triangle, rectangle, arc, draw text draw generate image (image) read generate PDF crop image custom UI control...
Quartz2D's value in iOS development
To facilitate the construction of a beautiful UI interface, iOS provides the UIKit framework, which has a variety of UI controls UILabel: display text UIImageView: display pictures

UIButton: displays images and text at the same time (can be clicked)
... ...

Using the controls provided by the UIKit framework, you can combine them to build simple and common UI interfaces.

However, some UI interfaces are extremely complex and personalized, and cannot be implemented using common UI controls. In this case, you can use Quartz2D technology to draw the internal structure of the controls, most of the controls in iOS are drawn from Quartz2D. Therefore, one of the important values of Quartz2D in iOS development is: Custom view (custom UI control)
Draw line segments (line width, line segment style, line color) in basic graphics)
Note: draw lines can only be drawn using a hollow style. CGContextStrokePath (ctx );
Example
-(Void) drawLine {// 1. obtain the graphic context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. concatenate a graph (PATH) // draw a straight line // set the starting position CGContextMoveToPoint (ctx, 10, 10); // Add a line segment to the point (100,100) CGContextAddLineToPoint (ctx, 100,100 ); // set the straight line width (yellow) // CGContextSetRGBStrokeColor (ctx, 0, 1, 0, 1); // set: Both hollow and solid colors // stroke: set the hollow color // fill: set the heartbleed color [[UIColor yellowColor] set]; // set the width of the line CGContextSetLineWidth (ctx, 10 ); // set the style (circle) CGContextSetLineCap (ctx, kCGLineCapRound) at the beginning of the line; // set the style (circle) CGContextSetLineJoin (ctx, kCGLineJoinRound) at the turning point of the line; // 3. CGContextStrokePath (ctx );}
Triangle example
-(Void) drawTriangle {// 1. obtain the graphic context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. stitch a graph (PATH) // draw a triangle // set the starting position CGContextMoveToPoint (ctx, 0, 0); // Add a line segment to the point (100,100) CGContextAddLineToPoint (ctx, 100,100 ); CGContextAddLineToPoint (ctx, 120, 20); CGContextClosePath (ctx); // you can specify the width of a straight line (red) [[UIColor redColor] set]. // set the line width CGContextSetLineWidth (ctx, 10); // set the line turning point style (aspect) CGContextSetLineJoin (ctx, kCGLineJoinBevel); // 3. CGContextStrokePath (ctx );}
Rectangle (hollow, solid, color) multiple ways to draw a rectangle
* Method 1 // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. draw four lines CGContextMoveToPoint (ctx, 10, 10); CGContextAddLineToPoint (ctx, 100, 10); CGContextAddLineToPoint (ctx, 100,100); CGContextAddLineToPoint (ctx, 10,100 ); CGContextClosePath (ctx); // 3. render CGContextStrokePath (ctx); * method 2 // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. draw CGContextAddRect (ctx, CGRectMake (10, 10,100,100); // 3. rendering CGContextStrokePath (ctx); * method 3 // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. draw and render CGContextStrokeRect (ctx, CGRectMake (10, 10,100,100); * method 4 // 1. obtain the context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. create path CGMutablePathRef path = CGPathCreateMutable (); CGPathAddRect (path, NULL, CGRectMake (10, 10,100,100); // 3. add the path to the context CGContextAddPath (ctx, path); CGPathRelease (path); // 4. rendering CGContextStrokePath (ctx); * Method 5 UIBezierPath * path = [UIBezierPathbezierPathWithRect: CGRectMake (10, 10,100,100)]; [path stroke];
Method description:
Void CGContextAddArc (CGContextRef c, CGFloat x, // The x coordinate CGFloat y of the center, // The x coordinate CGFloat radius of the center, // the radius of the circle CGFloat startAngle, // start radian CGFloat endAngle, // end radian int clockwise // 0 indicates clockwise, 1 indicates counterclockwise );
-(Void) drawCircle {// 1. obtain the graphic context CGContextRef ctx = UIGraphicsGetCurrentContext (); // 2. concatenate a graph // draw a circle CGContextAddEllipseInRect (ctx, CGRectMake (50, 50,100,100); // set the width CGContextSetLineWidth (ctx, 10); // set the color [[UIColor purpleColor] set]; // 3. rendering to View CGContextStrokePath (ctx );}

If you want to create a complete circle, the start radians are 0 and the end radians are 2pi.
Finally, after the function is executed, the current point is reset to (x, y ).

Note that if the current path already has a subpath,
The other result of this function execution is a straight line from the current point to the starting point of the arc.

Do not use C language functions to draw text and images (pattern. The reason is as follows: The Quarz2D drawing coordinate system is inconsistent with the UIKit coordinate system. As a result, text and image are reversed when you use the C language function to draw text and images. You need to write code to adjust it, use the knowledge of matrices in mathematics. Using C-language functions to draw text and Image Code is complex and difficult to understand. Very troublesome. Introduction to Graphics Context

Graphics Context: A CGContextRef type data.

The following figure indicates the role of the image to save the drawing information. The drawing status determines the output target of the drawing (where is the drawing going ?)
(The output target can be a PDF file, Bitmap, or display window)

For the same set of drawing sequences, different Graphics Context can be specified to draw the same image to different targets.

How can I use Quartz2D to draw a custom View? First, there must be a graphical context, because it can save the drawing information and decide where to draw. Second, the graphic context must be associated with the view, in order to create a class by drawing the content to the custom view above the view, inherit from the UIView implementation-(void) drawRect :( CGRect) rect method, then, in this method, obtain the graphic context associated with the current view and draw the corresponding graphic content. Use the graphic context to render all the drawn content to the view. drawRect: Why do you need to implement drawRect: how can I draw a graph to a view? Because the drawRect: method can obtain the graphic context drawRect associated with the view: When will the method be called? When the view is displayed on the screen for the first time (added to UIWindow)
Call setNeedsDisplay or setNeedsDisplayInRect: the context obtained in drawRect:

After obtaining the context in the drawRect: method, you can draw things to the view.

The View has a layer attribute. drawRect: The method obtains a Layer Graphics Context. Therefore, what you draw is actually drawn to the view layer.

The reason why a View can display things is entirely because of its internal layer

Drawing Sequence

Common splicing path Functions
Create a start void CGContextMoveToPoint (CGContextRef c, CGFloat x, CGFloat y) To add a new line segment to a certain point void CGContextAddLineToPoint (CGContextRef c, CGFloat x, CGFloat y) add a rectangle void CGContextAddRect (CGContextRef c, CGRect rect) add an elliptical void vertex (CGContextRef context, CGRect rect) add an arc void vertex (CGContextRef c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)
Common plot path Functions
The Mode parameter determines the rendering mode void CGContextDrawPath (CGContextRef c, quiet Mode). The void CGContextStrokePath (CGContextRef c) indicates the solid path void CGContextFillPath (CGContextRef c: generally, functions starting with CGContextDraw, CGContextStroke, and CGContextFill are used to draw paths.
Image context stack operations
Copy the current context and save it to the top of the stack (the stack is called the "graphic context stack"). void CGContextSaveGState (CGContextRef c) pulls the context at the top of the stack out of the stack, replace the current context void CGContextRestoreGState (CGContextRef c)
Matrix Operations

With matrix operations, all paths drawn to the context can change together.

Zoom
void CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy)

Rotate
void CGContextRotateCTM(CGContextRef c, CGFloat angle)

Translation
void CGContextTranslateCTM(CGContextRef c, CGFloat tx, CGFloat ty)

Quartz2D Memory Management

Objects Created using functions that contain "Create" or "Copy" must be released after use; otherwise, memory leakage will occur.

You do not need to release an object obtained by using a function that does not contain "Create" or "Copy ".

If an object is retained and is no longer used, you need to release it.

You can use the Quartz 2D function to specify the retain and release objects. For example, if a CGColorSpace object is created, the CGColorSpaceRetain and CGColorSpaceRelease functions are used to retain and release objects.

You can also use the CFRetain and CFRelease of the Core Foundation. Note that NULL values cannot be passed to these functions.

Watermarks for common example images: Translucent logos, text, and icons added to images to prevent others from stealing images

Watermark Function

Tell you where the image comes from
This is mainly because some websites are added for copyright issues and advertisements.

Sometimes, the watermark technology is also needed in the mobile client app.

For example, after taking a photo, you can add a watermark to the photo to identify the user of the image.

Implementation Method: Use Quartz2D to draw a watermark (text, LOGO) to the bottom right corner of the image

Core code
# Import UIImage + WHJ. h @ implementation UIImage (WHJ) + (instancetype) waterImageWithBg :( NSString *) bg logo :( NSString *) logo {UIImage * bgImage = [UIImage imageNamed: @ scene]; // 1. create a bitmap-based context (enable a bitmap-based context) // size: size of the new image // opaque: transparent. NO is not transparent, YES is transparent // scale: After this code is used, it is equivalent to creating a new bitmap, that is, the new UImage object uigraphicsbeginimagecontextwitexceptions (bgImage. size, NO, 0.0); // 1. image background [bgImage drawInRect: CGRectMake (0, 0, bgImage. size. width, bgImage. size. height)]; // 3. UIImage * waterImage = [UIImage imageNamed: @ logo]; CGFloat margin = 5; CGFloat scale = 0.5; CGFloat waterW = waterImage. size. width * scale; CGFloat waterH = waterImage. size. height * scale; CGFloat waterX = bgImage. size. width-waterW-margin; CGFloat waterY = bgImage. size. height-waterH-margin; [waterImage drawInRect: CGRectMake (waterX, waterY, waterW, waterH)]; // 4. obtain the created UIImage object UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); // 5. end context UIGraphicsEndImageContext (); return newImage ;}@ end
You can export images as png images.
// 6. view self. iconView. image = newImage; // 7. compress the image into PNG binary data NSData * data = UIImagePNGRepresentation (newImage); // 8. write File NSString * path = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @new.png]; [data writeToFile: path atomically: YES]; // NSLog (@ % @, path );
Crop an image to crop a normal image into a circle
// 1. obtain the image UIImage * image = [UIImage imageNamed: @ abc]; // 2. start image context UIGraphicsBeginImageContext (image. size); // circle // The context obtained by this code is the context CGContextRef ctx = UIGraphicsGetCurrentContext (); CGContextAddEllipseInRect (ctx, CGRectMake (0, 0, image. size. width, image. size. height); CGContextClip (ctx); // 3. draw an image [image drawAtPoint: CGPointZero]; // 4. obtain the image UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); self. iconView. image = newImage; // 5. disable the context UIGraphicsEndImageContext ();
Screenshots capture content on the screen
+ (Instancetype) catchImageWithView :( UIView *) view {// enable the graphic context UIGraphicsBeginImageContext (view. frame. size); // render the context content in the Controller to the View [view. layer renderInContext: UIGraphicsGetCurrentContext ()]; // obtain the image UIImage * newImage = watermark () from the graphic context; // disable the context UIGraphicsEndImageContext (); return newImage ;}

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.