iOS Learning Note 08-quartz2d drawing

Source: Internet
Author: User
Tags drawtext uikit

First, quartz2d simple introduction

The drawing framework commonly used in iOS is quartz2d,quartz2d is part of the core Graphics framework, and all of the Uikit components we use in our daily development are made up of core Graphics that are drawn

General steps for quartz2d drawing in iOS:
    1. Get Drawing context
    2. Create and set a path
    3. Add a path into the drawing context
    4. Setting Context State
    5. Draw Path
    6. Release path

Uikit default gives us a graphical context, called in the UI control's drawRect: method to UIGraphicsGetCurrentContext() get the graphics context

The following is a usage instance, defined within a custom UIView class:
#pragma mark Drawing-(void) DrawRect: (CGRect) rect{Drawing can only be called in this method, otherwise the current drawing context cannot be obtained1. Get the Graphics context objectCgcontextref context =Uigraphicsgetcurrentcontext ();2. Create a Path objectCgmutablepathref Path =Cgpathcreatemutable ();Cgpathmovetopoint (Path,Nil20,50);Move to the specified location (set path start point)Cgpathaddlinetopoint (Path,Nil20,100);Draw a line (starting from the starting position)Cgpathaddlinetopoint (Path,Nil300,100);Draw another line (starting at the end of the line)3. Add a path to the graphics contextCgcontextaddpath (context, path);4. Setting the graphics context State propertiesCgcontextsetrgbstrokecolor (Context,1.0,0,0,1);Set Stroke colorCgcontextsetrgbfillcolor (Context,0,1.0,0,1);Set Fill ColorCgcontextsetlinewidth (Context,2.0);Set line widthCgcontextsetlinecap (context, KCglinecapround);Set vertex stylesCgcontextsetlinejoin (context, KCglinejoinround);Set connection point Styles/* Set line segment style Cgcontextsetlinedash (context, phase, lengths, count); Phase: Dashed start position lengths: Dash length interval count: Number of dashed array elements */CGFloat lengths[2] = {18,9};Cgcontextsetlinedash (Context,0, lengths,2);/* Set Shadow Cgcontextsetshadowwithcolor (context, offset, blur, color); Offset: offset Blur: Ambiguity color: Shadow color */cgcolorref color = [uicolor graycolor]. Cgcolor; //quartz2d is a cross-platform, using the C language cgcontextsetshadowwithcolor (context, Cgsizemake (2, 2), 0.8, color); //5. Drawing an image to a specified graphics context/ * Fill mode Cgpathdrawingmode Kcgpathfill: Only fills (not 0 winding number fills), no border Kcgpatheofill: odd-even rule fills (when multiple paths intersect, Odd cross fill, even cross not filled) Kcgpathstroke: only border Kcgpathfillstroke: both border and fill kcgpatheofillstroke: odd and even fills and draws a border * / Cgcontextdrawpath (context, Kcgpathfillstroke);  The last parameter is the fill type //6. Release Path Object cgpathrelease (path);            

The drawing process above is too cumbersome, so Apple encapsulates some of the drawing methods in the Uikit framework

- (void) DrawRect: (CGRect) rect{1. Get the graphics contextCgcontextref context =Uigraphicsgetcurrentcontext ();2. Add a path (equivalent to creating a path earlier and adding a path to the graphics context two steps)Cgcontextmovetopoint (Context,20, 50); cgcontextaddlinetopoint (context, 20, 100); cgcontextaddlinetopoint (context, 300, 100); //closed path: Direct call path closure method cgcontextclosepath (context); //3. Setting the graphics context properties [[uicolor Redcolor] setstroke]; Set red Border [[uicolor Greencolor] setfill]; Set Green fill //[[uicolor Bluecolor] set];//set both fill and border color //4. Draw path Span class= "hljs-built_in" >cgcontextdrawpath (context, Kcgpathfillstroke);}    
Second, the basic graphics of the drawing method
# Draw RectangleCgcontextaddrect (Cgcontextref context,CGRect rect);Uirectfill (CGRect rect);Only fillsUirectframe (CGRect rect);Only borders# Draw EllipseCgcontextaddellipseinrect (Cgcontextref context,CGRect rect);# Draw radians/* Context: Draw context x: center point x coordinate y: Center point Y coordinate radius: Radius startangle: Starting Radian, 0 means the rightmost start of the Circle Endangle: terminating radians, positive values are calculated clockwise Closewise: whether to draw counterclockwise, 0 draw Clockwise */Cgcontextaddarc (Cgcontextref context,CGFloat x,CGFloat y,CGFloat radius,CGFloat StartAngle,CGFloat Endangle,int closewise);# Plot two Bezier curves/* Context: Graphics context CPX: Control point x Coordinate cpy: Control point y coordinate x: end point x coordinate y: End point y coordinate */cgcontextref context,  CGFloat CPX, cgfloat cpy, cgfloat x, cgfloat y); # plot three Bezier curves /* Context: Graphics context cp1x: First control point x coordinate cp1y: First control point y-coordinate cp2x: Second control point x coordinate cp2y: Second control point y coordinate x: end point x coordinate y: End point y coordinate */cgcontextaddcurvetopoint (cgcontextref context, cgfloat cp1x, CGFloat cp1y, cgfloat cp2x, cgfloat cp2y, cgfloat x, cgfloat y);       

Iii. drawing text and images
#pragma mark Drawing-(void) DrawRect: (CGRect) rect{1. Get the graphics contextCgcontextref context =Uigraphicsgetcurrentcontext (); [Self Drawtext:context]; [Self drawimage:context];}#pragma mark draws text-(void) DrawText: (CGCONTEXTREF) context{Draw to the specified area contentNSString *str =@ "Star Walk is the most beautiful ... sdadasd dsadsa";CGRect rect =CGRectMake (20,40M280,300);Uifont *font = [Uifont systemfontofsize:18];Set fontUicolor *color = [Uicolor Redcolor];Font ColorNsmutableparagraphstyle *style = [[Nsmutableparagraphstyle alloc] init];Paragraph Style style.alignment =Nstextalignmentleft;alignment [STR drawinrect:rect withattributes:@{Nsfontattributename:font,Nsforegroundcolorattributename:color,Nsparagraphstyleattributename:style}];}#pragma mark to draw a picture-(void) DrawImage: (cgcontextref) context{ uiimage *image = [uiimage imagenamed: @ "image2.jpg"]; //draw from a point [image Drawatpoint:cgpointmake (10, 50)]; //drawn into the specified rectangle, note that if the size is not appropriate, it will be stretched and the image will be deformed [image drawinrect:10, 50, 300, 450)]; //tile drawing [Image Drawaspatterninrect:cgrectmake (0, 0, 320, 568)];}   

In fact there are some drawing methods, such as, 渐变填充 叠加模式 and 填充模式 , but these things do not use much, here is not detailed, interested I might write another note for these drawing techniques.
You can refer to the following effects:

Four, the shape of the context deformation

quartz2d coordinate system Uikit is not the same, its coordinates origin in the lower left corner of the screen, Uikit to convert it, coordinate Origin unified in the upper left corner of the screen

We can also operate on a coordinate system:
#pragma mark Graphics Context deformation-(void) DrawRect: (CGRect rect) {Cgcontextref context =Uigraphicsgetcurrentcontext ();Save Initial stateCgcontextsavegstate (context);The first step of deformation: The graphics context pans right 40CGCONTEXTTRANSLATECTM (context, 100, 0); //deformation Step Two: Zoom 0.8 CGCONTEXTSCALECTM (context, 0.8, 0.8); //deformation step three: Rotate CGCONTEXTROTATECTM (context, M_pi_4/4); uiimage *image = [uiimage imagenamed: @ "photo1.jpg"]; [Image Drawinrect:cgrectmake (0,  240, 300)]; //revert to the initial state cgcontextrestoregstate (context);}     
    • Before setting the shape context, be sure to remember the initial state of the save context and recover after use
    • In iOS development, developers are not allowed to call drawRect: methods directly, and refreshing drawing content requires calling setNeedsDisplay methods.
V. Other drawing context bitmap contexts:
# 开启位图上下文,没有返回值UIGraphicsBeginImageContext(CGSize size);# 在开启位图上下文和关闭位图上下文之间,使用该方法获取位图上下文UIGraphicsGetCurrentContext()# 关闭位图上下文,没有返回值UIGraphicsEndImageContext()
PDF Context:
# 开启PDF上下文,没有返回值/*     path : 保存路径     bounds : pdf文档大小,如果设置为CGRectZero,则使用默认值:612*792     pageInfo : 页面设置,为nil则不设置任何信息*/UIGraphicsBeginPDFContextToFile(NSString *path, CGRect bounds, NSDictionary *pageInfo);# 在开启PDF上下文和关闭PDF上下文之间,使用该方法获取PDF上下文UIGraphicsGetCurrentContext()# 关闭PDF上下文,没有返回值UIGraphicsEndPDFContext()

How do we know we're drawing a success?

For PDF, we can open the pdf file for bitmap, we can save the drawn bitmap as a picture object uiimage
# 返回绘制的新图像UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
A small tip for PDF drawing, which is the pagination of a PDF
# 开启一个PDF新页,调用了该方法,以后的绘图操作都是在新页上绘制的IGraphicsBeginPDFPage()

iOS Learning Note 08-quartz2d drawing

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.