Quartz 2D Learning Record Quartz 2D Brief Introduction One, what is Quartz 2D
Quarz 2D is a two-dimensional painting engine that supports both iOS and Mac, and its API is the core graphics framework and is pure C language. Most of the controls provided by the iOS system are drawn through quartz 2D, so an important value for quartz 2D is to customize the view (custom UI controls).
Second important concepts: graphics contexts
The graphics context is a CGCONTEXTREF data that acts as:
- Save drawing information, drawing properties
- Draw a target pattern
- Output the plotted pattern to the output target, i.e. where to go (can be a PDF file, bitmap, or a display window)
Third, custom view, that is, drawing view
Implement-(void) DrawRect: (CGRect) Rect method in view, and then in the method:
1. Obtain a graphical context associated with the current view;
2. Draw the appropriate graphic content
3. Render the rendered graphic content to the view using the graphical context
Quartz 2D Simple Use code example
//Draw step: 1, get the current view of the graphics context 2, start drawing 3, render the drawing content /** drawing a straight line **/ ///1, gets the graphical context of the current view (the drawing context determines the output target to be drawn)Cgcontextref CTX = Uigraphicsgetcurrentcontext ();//2, start drawing //Set the starting pointCgcontextmovetopoint (CTX, -, -);//Set end pointCgcontextaddlinetopoint (CTX, -, -);//Set line Properties //Set colorCgcontextsetstrokecolorwithcolor (CTX, [Uicolor Purplecolor]. Cgcolor);//Another way to set colors//[[Uicolor Purplecolor] set]; //Set line widthCgcontextsetlinewidth (CTX,Ten);//Set the line start and end style to rounded cornersCgcontextsetlinecap (CTX, Kcglinecapround);///3. Render the content drawn on the canvas to the layer on the ViewCgcontextstrokepath (CTX);/** Draw Triangle **/ //Set the starting pointCgcontextmovetopoint (CTX, Max, the);//Set a first inflection pointCgcontextaddlinetopoint (CTX, -, Max);//Set a second inflection pointCgcontextaddlinetopoint (CTX, the, Max);//Set a third point (end)//Cgcontextaddlinetopoint (CTX, N.); //You can use the following method instead of the stitch start and end pointCgcontextclosepath (CTX);//Set the inflection point corner style for the line to roundedCgcontextsetlinejoin (CTX, Kcglinejoinround);//RenderingCgcontextstrokepath (CTX);/** Drawing Hollow Quadrilateral **/Cgcontextaddrect (CTX, CGRectMake ( +, $, $, -));//Set hollow (line) color//Cgcontextsetstrokecolorwithcolor (CTX, [Uicolor Lightgraycolor]. Cgcolor); //You can also set colors like this[[Uicolor Lightgraycolor] setstroke];//Set line widthCgcontextsetlinewidth (CTX,Ten);//rendering (hollow)Cgcontextstrokepath (CTX);/** Drawing solid quadrilateral **/Cgcontextaddrect (CTX, CGRectMake ( +, the, $, -));//Set solid color//Cgcontextsetfillcolorwithcolor (CTX, [Uicolor Orangecolor]. Cgcolor);[[Uicolor Orangecolor] setfill];//render (solid)Cgcontextfillpath (CTX);/** Draw a circle (you can draw a circle by drawing an ellipse) **/ //parameters are Center x, center y, radius, arc of start position, arc of end position, draw path (1 clockwise, 0 counterclockwise) //Because the quartz2d coordinate system is the x-axis to the right and the y-axis upward, unlike the Uikit coordinate system. Therefore, when the quartz2d coordinate system is not flipped, the drawing is symmetric with the original graph about the x-axis. Cgcontextaddarc (CTX, -,520, -,0, M_pi_2,1); Cgcontextstrokepath (CTX);//Hollow//Cgcontextfillpath (CTX); //Solid /** drawing Ellipse **/Cgcontextaddellipseinrect (CTX, CGRectMake ( the, -, -, $)); Cgcontextsetstrokecolorwithcolor (CTX, [Uicolor Bluecolor]. Cgcolor); Cgcontextstrokepath (CTX);/** plotting arcs **///Cgcontextaddarctopoint (CTX, n , Max, +, +);Cgcontextaddarc (CTX, $, $, -,0, M_PI,1); Cgcontextsetstrokecolorwithcolor (CTX, [Uicolor Cyancolor]. Cgcolor); Cgcontextstrokepath (CT
Drawing results
Graph context stack one, drawing principle
For example, if you want to draw two lines, a red one is the default black. Draw the Red line first, draw the finished rendering, then draw the second one. If you do not re-set the painting color when you draw the second bar, the drawn lines are also red. That is, if the drawing property is not emptied (that is, reset) it is left on the graphics context by default. So it can be understood that:
A graphical context has 3 areas, namely, drawing properties, image information, drawing areas:
- Draw Properties : including the color of the brush, line width, whether rounded corners and so on;
- Drawing Information : For example, to draw a line, then save the beginning and end of the line, draw a circle, save the radius, midpoint coordinates, start point, direction and so on. In other words, the drawing information is saved in the drawing path, which is described in detail below.
- Drawing Area : This area does not refer to the area on the view, but to the drawing area on the graphics context, because the drawing is drawn on the graphics context before it is rendered to the development area of the view.
Second, save the drawing context drawing properties
As I said earlier, if you want to draw multiple graphs with different properties, you will have to re-set the drawing properties each time you render a graphic, usually drawing multiple graphs. Sometimes it is possible to use a simple method: to save the drawing property in the context of the current drawing before drawing a graph, the drawing attribute will be saved to the graph context stack, and if you need to draw the graph of the same property next time, you can simply remove the drawing attribute from the top of the stack (restore). It is important to note that the save can only be taken once, and may be saved multiple times, but only from the top of the stack at a time .
code example
/**保存绘制属性(以绘制3条线为例,第一条第三条属性一致)**///第一条CGContextMoveToPoint(ctx, 20, 300);CGContextAddLineToPoint(ctx, 200,300);//设置绘制属性CGContextSetLineWidth(ctx, 10);CGContextSetLineCap(ctx, kCGLineCapRound);CGContextSetStrokeColorWithColor(ctx, [UIColor orangeColor].CGColor);CGContextStrokePath(ctx);//第二条线//先保存当前的绘制属性CGContextSaveGState(ctx);CGContextMoveToPoint(ctx, 20, 400);CGContextAddLineToPoint(ctx, 200, 400);//设置新的绘制属性CGContextSetLineWidth(ctx, 5);CGContextSetLineCap(ctx, kCGLineCapButt);CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor);CGContextStrokePath(ctx);//第三条线//取出(恢复)之前保存的绘制属性CGContextRestoreGState(ctx);CGContextMoveToPoint(ctx, 20, 500);CGContextAddLineToPoint(ctx, 200, 500);CGContextStrokePath(ctx);
Drawing results
Matrix operation one, matrix operation introduction
The matrix operation mainly has the rotation operation, the scale operation, the translation operation, is in the view upper left corner is the origin point . The operation of the matrix must be done before drawing , otherwise the operation is invalid after drawing.
Second, the code description
Cgcontextref CTX = Uigraphicsgetcurrentcontext ();//Matrix rotation 45 degrees (parameter is the graph context, rotation angle) is the top left corner of the rotation point //Set the matrix operation to be completed before drawing//CGCONTEXTROTATECTM (CTX, m_pi_4); //Zoom (parameter is graphics context, X-direction scale, Y-direction scale)//CGCONTEXTSCALECTM (CTX, 0.5, 0.5); //pan (parameter is graphics context, X-direction shift distance, y-direction translation distance)CGCONTEXTTRANSLATECTM (CTX, -, -); Cgcontextaddrect (CTX, CGRectMake ( -, -, -, -));//Mark NSString*loc1 = @"1";NSString*LOC2 = @"2"; [Loc1 Drawatpoint:cgpointmake ( About, About) Withattributes:Nil]; [Loc2 Drawatpoint:cgpointmake (201, About) Withattributes:Nil]; Cgcontextstrokepath (CTX);
Cut operation one, cut introduction
Cut out the unexpected part of the specified area, leaving only the content within that area.
principle : First set the cutting area, or cut the method, then to draw the relevant content.
Second, code-related
Cgcontextref CTX = Uigraphicsgetcurrentcontext ();//Cut the unexpected part of the custom area (with the cut as a triangle, cut the content as an example of the picture)///// Cgcontextaddellipseinrect (CTX, CGRectMake ( +, +, +));//Cgcontextmovetopoint (CTX, +);//Cgcontextaddlinetopoint (CTX, max);//Cgcontextaddlinetopoint (CTX, N.);//Cgcontextclosepath (CTX);//Cgcontextclip (CTX); //Cut the unexpected part of the specified rectangular areaCgcontextcliptorect (CTX, CGRectMake ( the, -,Ten,Ten));UIImage*image = [UIImageimagenamed:@"Google"]; [Image Drawatpoint:cgpointmake ( the, -)];
Drawing path One, drawing path introduction
Before we draw a straight line, we set its starting point and end point directly, and then we begin to draw it. Draw a circle, set the center radius start point and direction. In fact, after we set up the drawing information, a drawing path is created by default, and drawing is drawn according to this path. One line corresponds to one path, and one circle corresponds to another. Then we can naturally draw by creating a path manually, we need to draw several patterns, we will create a few paths.
Second, the attention point
All values created by the Creat/copy/retain method in A, quartz2d, are freed, taking path as an example:
- Cgpathrelease (path);
- Cfrelease (path);
B. Once all the paths that you want to draw are added to the graphics context, the last one is rendered.
Third, code example
two ways to draw a line (two ways are equivalent)Cgcontextref CTX = Uigraphicsgetcurrentcontext (); Cgcontextmovetopoint (CTX, -, $); Cgcontextaddlinetopoint (CTX, -, $); Cgcontextstrokepath (CTX);//Create path drawing manually //Create a pathCgmutablepathref path = cgpathcreatemutable ();//Add drawing information to pathCgpathmovetopoint (Path,NULL, -, -); Cgpathaddlinetopoint (Path,NULL, -, -);//Add a path to the graphics contextCgcontextaddpath (CTX, path);//Create another pathCgmutablepathref path2 = cgpathcreatemutable (); Cgpathaddellipseinrect (path2,NULL, CGRectMake ( -, -, -, -)); Cgcontextaddpath (CTX, path2); Cgcontextstrokepath (CTX);//render the pattern corresponding to all pathsCgcontextstrokepath (CTX);all values created by the Creat/copy/retain method in the//quartz2d are releasedCgpathrelease (path); Cgpathrelease (path2);//or//Cfrelease (path);
Run results
Bitmap one, bitmap graphics context
QUARTZ2D provides the following types of graphics contexts
- Bitmap Graphics Context
- PDF Graphics Context
- Window Graphics Context
- Layer Graphics Context
- Printer Graphics Context
Commonly used is the bitmap Graphics Context. The so-called bitmap, in fact, is UIImage, which is also the most commonly used in the graphical context, usually used to generate a picture. The steps are as follows:
Create a bitmap graphics context (in two ways)
A.uigraphicsbeginimagecontext (< #CGSize size#>);
B.uigraphicsbeginimagecontextwithoptions (cgsize size, BOOL opaque, cgfloat scale);
Both of these methods can create a bitmap graphics context, but the first creates a picture with no second good clarity and quality. The parameters of the method two receive are:
- Size: Specifies the size of the bitmap size created
- Opaque: transparent, yes = opaque, no transparent
- Scale: Zoom, 0 is not scaled
Get the created bitmap graphics context and make a fuss over it (paint)
- Take out the drawn picture
- Close the bitmap graphics context
- Releasing the variables that need to be freed
code example (screenshot)
//Click the button to intercept the screen- (void) Actionshot: (UIButton*) sender{//You can hide the button and show it back when finished rendering Self. Buttonshot. Hidden=YES;//Create a graphics contextUigraphicsbeginimagecontextwithoptions (Cgsizemake ( Self. View. Frame. Size. Width, Self. View. Frame. Size. Height),NO,0);//Gets the graphics context and renders the current screen to the graphics contextAppdelegate *delegate = (appdelegate *) [uiapplicationSharedapplication]. Delegate; [Delegate. Window . LayerRenderincontext:uigraphicsgetcurrentcontext ()];//Remove the drawn picture from the graphics context UIImage*screenimage = Uigraphicsgetimagefromcurrentimagecontext ();//Close the graphics contextUigraphicsendimagecontext (); Self. Buttonshot. Hidden=NO;//// screen complete Sometimes you might want to get a picture of a specified area on the screen, as follows//// Get screenshot of CgimageCgimageref image = Screenimage. Cgimage;//Set the target area, note that there is a need to consider the magnification of the retina resolution, taking iphone6plus as an example, on the basis of the original size, it is not judged here. CGRectRect = CGRectMake (0,0, Screenimage. Size. Width*3, Screenimage. Size. Height*3);//Remove picture of target areaCgimageref targetimage = cgimagecreatewithimageinrect (image, Rect);//Final picture UIImage*finalimage = [UIImageImagewithcgimage:targetimage];//Save to albumUiimagewritetosavedphotosalbum (Finalimage, Self,@selector(Image:didFinishSavingWithError:contextInfo:),Nil);//Save to sandbox NSString*path = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Firstobject]; NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init]; [Dateformatter setdateformat:@"Yyyy-mm-dd HH:mm:ss"];NSString*currenttime = [Dateformatter stringfromdate:[NSDateDate]];NSString*imagepath = [path stringbyappendingpathcomponent:[NSStringstringwithformat:@"Screenshot_%@.png", CurrentTime]]; NSData *imagedate = uiimagepngrepresentation (finalimage); [Imagedate Writetofile:imagepath atomically:YES]; Cgimagerelease (targetimage);}
//callback after saving to album- (void) Image: (UIImage*) Image didfinishsavingwitherror: (Nserror*) Error ContextInfo: (void*) contextinfo{NSString*msg =Nil;if(Error! =NULL) {msg = @"Save picture Failed"; }Else{msg = @"Save picture succeeded"; } Uialertview *alert = [[Uialertview alloc] initwithtitle:@"Save picture result hint"Message:msg Delegate: Selfcancelbuttontitle:@"OK"Otherbuttontitles:Nil]; [Alert show];}
QUARTZ2D Memory Management
In front of the drawing path referred to memory management, the following summary:
- Any object created with a function that contains "create" or "Copy" must be released after use, otherwise it will cause a memory leak. Does not contain "create" or "copy", it does not need to be released.
- If an object is retain, release is required when it is no longer in use. As an example, if you create a Cgcolorspace object, use the function Cgcolorspaceretain and cgcolorspacerelease to retain and release the Cgcolorspace object. You can also use the Cfretain and cfrelease of the core Foundation. Note You cannot pass null values to these functions.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS Development-quartz 2D Introduction