Drawing-quartz2d-in iOS development

Source: Internet
Author: User
Tags uikit

Reprint Please specify source: http://blog.csdn.net/whjForWork/article/details/44926763

What is quartz2d

Quartz 2D is a two-dimensional drawing engine that supports both iOS and Mac systems

Role
The value of quartz2d in iOS development
  • To make it easy to build an aesthetically pleasing UI, iOS provides a uikit framework with a variety of UI controls
  • UILabel: Display text
  • Uiimageview: Show Pictures
  • UIButton: Simultaneous display of pictures and text (can be clicked)
    ... ...

  • Use the controls provided by the Uikit framework to cobble together, build and present some simple, common UI interfaces

  • However, some UI interfaces are extremely complex and more personalized and cannot be implemented with normal UI controls, so you can use quartz2d technology to draw the structure inside the control and customize what the control looks like
  • In fact, the content of most controls in iOS is drawn through quartz2d, so quartz2d is an important value in iOS development: Custom view (custom UI controls)
Basic graphics Draw segments (line width, segment style, line color)
注意点:画线条只能通过空心样式画。CGContextStrokePath(ctx);
Example
-(void) drawline{//1. Obtaining a Graphics contextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. Stitching graphics (path)    //Draw a straight line    //Set start positionCgcontextmovetopoint (CTX,Ten,Ten);//Add a line segment to point (100,100)Cgcontextaddlinetopoint (CTX, -, -);//Set the width of the line (yellow)    //cgcontextsetrgbstrokecolor (CTX, 0, 1, 0, 1);    //set: Set to both hollow and solid colors    //stroke: Setting the hollow color    //fill: Setting the color of the Lost heart[[Uicolor Yellowcolor]Set];//Set the width of the lineCgcontextsetlinewidth (CTX,Ten);//Set the style at the beginning of the line (circle)Cgcontextsetlinecap (CTX, Kcglinecapround);//Set the style of the line Turning Point (circle)Cgcontextsetlinejoin (CTX, Kcglinejoinround);//3. Render display to view aboveCgcontextstrokepath (CTX);}
Triangle Example
-(void) drawtriangle{//1. Obtaining a Graphics contextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. Stitching graphics (path)    //Draw a triangle    //Set start positionCgcontextmovetopoint (CTX,0,0);//Add a line segment to point (100,100)Cgcontextaddlinetopoint (CTX, -, -); Cgcontextaddlinetopoint (CTX, -, -); Cgcontextclosepath (CTX);//Set the width of the line (red)[[Uicolor Redcolor]Set];//Set the width of the lineCgcontextsetlinewidth (CTX,Ten);//Set the style of the line turning point (tangent)Cgcontextsetlinejoin (CTX, kcglinejoinbevel);//3. Render display to view aboveCgcontextstrokepath (CTX);}
Rectangles (hollow, solid, color) draw rectangles in a variety of ways
* Way One//1. Get ContextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. Draw four linesCgcontextmovetopoint (CTX,Ten,Ten); Cgcontextaddlinetopoint (CTX, -,Ten); Cgcontextaddlinetopoint (CTX, -, -); Cgcontextaddlinetopoint (CTX,Ten, -); Cgcontextclosepath (CTX);//3. RenderingCgcontextstrokepath (CTX); * Way Two//1. Get ContextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. DrawingCgcontextaddrect (CTX, CGRectMake (Ten,Ten, -, -));//3. RenderingCgcontextstrokepath (CTX); * Way Three//1. Get ContextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. Draw and RenderCgcontextstrokerect (CTX, CGRectMake (Ten,Ten, -, -)); * Mode Four//1. Get ContextCgcontextref CTX = Uigraphicsgetcurrentcontext ();//2. Create a pathCgmutablepathref path = cgpathcreatemutable (); Cgpathaddrect (Path,NULL, CGRectMake (Ten,Ten, -, -));//3. Add path to ContextCgcontextaddpath (CTX, path); Cgpathrelease (path);//4. RenderingCgcontextstrokepath (CTX); * Way five Uibezierpath *path = [Uibezierpathbezierpathwithrect:cgrectmake (Ten,Ten, -, -)]; [Path stroke];
Ellipse \ Circle \ Arc \ Pie chart
    • Drawing Arc Method Description:
voidCGFloat x,             //圆心的x坐标CGFloat y,    //圆心的x坐标CGFloat radius,   //圆的半径CGFloat startAngle,    //开始弧度CGFloat endAngle,   //结束弧度int clockwise          //0表示顺时针,1表示逆时针);
-(void ) drawcircle{//1. Get the graphics context  cgcontextref CTX = Uigraphicsgetcurrentcontext ();    //2. Stitching graphics     //draw a circle  Cgcontextaddellipseinrect (CTX, CGRectMake (50 , 50    , 100 , 100 ));    //set width     Cgcontextsetlinewidth (CTX, 10 );    //set color     [[Uicolor Purplecolor]set ];    //3. Render to view  Cgcontextstrokepath (CTX);}  

If you want to create a complete circle, then the starting radian is the 0 end Radian is 2pi
Finally, when the function finishes executing, the current point is reset to (x, y).

It is also important to note that if there is already a subpath in the current path,
Then another effect of this function is to have a straight line from the current point to the beginning of the arc.

Text Drawing and picture drawing (pattern) draw text and pictures do not use C functions. The reasons are as follows:
    • The quarz2d drawing coordinate system and the UIKit coordinate system are inconsistent, resulting in the use of C language functions to draw text and pictures will appear inverted text and picture phenomenon, need to write code adjustment, to take advantage of the knowledge of the matrix in mathematics.
    • Using C-language functions to draw text and picture code is complicated and the function is poorly understood. Very troublesome.
Introduction to Graphic context (graphics contexts)

Graphics context: is a cgcontextref type of data

The role of the graphical upstream context
    • Save drawing information, drawing status
    • Decide where to draw the output target (where to draw?) )
      (The output target can be a PDF file, a bitmap or a display window)

    • The same set of drawing sequences, specifying different graphics Context, can draw the same image to different targets

Customize view how do I draw things to the view using quartz2d?
    • First, you have to have a graphical context, because it saves the drawing information and determines where to draw it.
    • Second, the graphics context must be associated with the view to draw the content to the view
Steps to customize view
    • Create a new class that inherits from UIView
    • Implement-(void) DrawRect: (CGRect) Rect method, and then in this method
    • Gets the graphics context associated with the current view
    • Draw the appropriate graphic content
    • Renders all rendered content to the view using a graphical context
DrawRect: Why do you want to implement DrawRect: How can I draw to a view?
    • Because the graphics context associated with the view can be obtained in the DrawRect: method
DrawRect: When is the method called?
    • When view is first displayed on the screen (added to UIWindow)
      Call view's Setneedsdisplay or Setneedsdisplayinrect: when
DrawRect: Context acquired in
    • After you get the context in the DrawRect: method, you can draw something to the view

    • There is a layer property inside the view, DrawRect: A layer Graphics Context is obtained in the method, so the drawing is actually drawn to the view layer.

    • View is able to show things entirely because of its inner layer

Drawing order

Common Stitching path function
Create a new starting pointvoidCgcontextmovetopoint (Cgcontextref C,CGFloatXCGFloatY) Add a new segment to a pointvoidCgcontextaddlinetopoint (Cgcontextref C,CGFloatXCGFloatY) Add a rectanglevoidCgcontextaddrect (Cgcontextref C,CGRectRect) Add an ellipsevoidCgcontextaddellipseinrect (Cgcontextref context,CGRectRECT) Add an arcvoidCgcontextaddarc (Cgcontextref C,CGFloatXCGFloatYCGFloatRadiusCGFloatStartAngle,CGFloatEndangle,intclockwise)
Common Drawing Path functions
Mode参数决定绘制的模式void CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode)绘制空心路径void CGContextStrokePath(CGContextRef c)绘制实心路径void CGContextFillPath(CGContextRef c)提示:一般以CGContextDraw、CGContextStroke、CGContextFill开头的函数,都是用来绘制路径的
Operation of the graphics context stack
将当前的上下文copy一份,保存到栈顶(那个栈叫做”图形上下文栈”)void CGContextSaveGState(CGContextRef c)将栈顶的上下文出栈,替换掉当前的上下文void CGContextRestoreGState(CGContextRef c)
Matrix operations
    • A matrix operation that allows all paths drawn to the context to be changed together

    • Scaling
      void CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy)

    • Rotating
      void CGContextRotateCTM(CGContextRef c, CGFloat angle)

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

QUARTZ2D Memory Management
    • objects created with a function that contains "create" or "Copy" must be freed after use, or a memory leak will result

    • Object obtained with a function that does not contain "Create" or "Copy", you do not need to release

    • If an object is retain and is no longer in use, you need to release it

    • You can use the Quartz 2D function to specify retain and release an object. For example, if you create a Cgcolorspace object, use the functions Cgcolorspaceretain and cgcolorspacerelease to retain and release the object.

    • You can also use the Cfretain and cfrelease of the core Foundation. Note You cannot pass null values to these functions

Common Example Picture watermark
    • Watermark: A translucent logo, text, or icon added to the image to prevent others from stealing pictures
    • The role of watermarks

      I'll tell you where this picture came from.
      Some websites are added for copyright issues and ads.

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

    • For example, when a user finishes a photo, a watermark can be printed on the photo to identify which user the image belongs to.

    • Implementation: Using QUARTZ2D, the watermark (text, LOGO) to the bottom right corner of the picture

Core code
#import "uiimage+whj.h"  @implementation UIImage (whj)+ (Instancetype) WATERIMAGEWITHBG: (NSString*) BG Logo: (NSString*) logo{UIImage*bgimage = [UIImageimagenamed:@"Scene"];//1. Creating a bitmap-based context (opening a bitmap-based context)    //size: Size of new picture    //opaque: Transparent. No is opaque, yes is transparent    //scale: Zooming    //This code is equivalent to creating a new bitmap, which is the new Uimage objectUigraphicsbeginimagecontextwithoptions (bgimage. Size,NO,0.0);//1. Painting Background[Bgimage Drawinrect:cgrectmake (0,0, Bgimage. Size. Width, Bgimage. Size. Height)];//3. Draw the watermark in the lower right corner    UIImage*waterimage = [UIImageimagenamed:@"logo"];CGFloatmargin =5;CGFloatScale =0.5;CGFloatWATERW = Waterimage. Size. Width* SCALE;CGFloatWaterh = Waterimage. Size. Height* SCALE;CGFloatWaterx = Bgimage. Size. Width-Waterw-margin;CGFloatwatery = Bgimage. Size. Height-Waterh-margin; [Waterimage Drawinrect:cgrectmake (Waterx, watery, waterw, Waterh)];//4. UIImage object made from the context    UIImage*newimage = Uigraphicsgetimagefromcurrentimagecontext ();//5. End ContextUigraphicsendimagecontext ();returnNewImage;}@end
You can export a picture as a PNG image
    //6.显示到View    self.iconView.image = newImage;    //7.将image压缩为PNG格式的二进制数据    NSData * data = UIImagePNGRepresentation(newImage);    //8.写入文件    NSStringYES)lastObject]stringByAppendingPathComponent:@"new.png"];    [data writeToFile:path atomically:YES];    //    NSLog(@"%@",path);
Picture clipping cuts a normal picture to a circle
    //1. Getting pictures    UIImage*image = [UIImageimagenamed:@"ABC"];//2. Start Picture ContextUigraphicsbeginimagecontext (image. Size);//Draw a circle    The context that this code obtains is the context in which the previous code beganCgcontextref CTX = Uigraphicsgetcurrentcontext (); Cgcontextaddellipseinrect (CTX, CGRectMake (0,0, image. Size. Width, image. Size. Height)); Cgcontextclip (CTX);//3. Drawing pictures[Image Drawatpoint:cgpointzero];//4. Getting pictures    UIImage*newimage = Uigraphicsgetimagefromcurrentimagecontext (); Self. IconView. Image= NewImage;//5. Closing the contextUigraphicsendimagecontext ();
Screenshot captures what's on the screen
+(instancetype)catchImageWithView:(UIView *)view{    //开启图形上下文    UIGraphicsBeginImageContext(view.frame.size);    //将控制器中上下文的内容渲染到View中    [view.layer renderInContext:UIGraphicsGetCurrentContext()];    //从图形上下文获得图片    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    //关闭上下文    UIGraphicsEndImageContext();    return newImage;}

Drawing-quartz2d-in iOS development

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.