Core Graphics framework and coregraphics framework

Source: Internet
Author: User

Core Graphics framework and coregraphics framework

The commonly used framework in iOS is Quartz 2D, which is part of the Core Graphics Framework and is a powerful Two-Dimensional Image Rendering Engine. The UIKit components used in our daily development are all drawn by the Core Graphics framework. When we import the UIKit framework, the Core Graphics framework is automatically imported.

In iOS, plotting is generally divided into the following steps:

1. Get the drawing Context

2. Create and set the path

3. Add the path to the context

4. Set the context status

5. Draw a path

6. Release path

In the graph context, CGContextRef indicates the image output device, that is, the drawing position. It contains some device information about the drawing. All objects in Quartz 2D must be added to the graph context, in this way, we do not need to relate the specific device information when drawing the image.

Basic Drawing

In UIKit, we have prepared a graphical context object by default. In the drawrect method of UIView, we can obtain the graphic context through the UIGraphicsGetCurrentContext () method of the UIKit encapsulation function (note: can not be obtained in other methods), and then you only need to follow the drawing steps step by step, the following override view drawrect method, add two lines on the view:

Override func draw (_ rect: CGRect) {// 1. obtain the graphic context object let contextRef = UIGraphicsGetCurrentContext () // 2. create the path object let path = CGMutablePath () path. move (to: CGPoint (x: 10, y: 10) path. addLine (to: CGPoint (x: 100, y: 100) // This code is used to draw a curve. lengths indicates that the length of each segment of the dotted line is 5, the spacing of each segment is 1. If phase is set to 2, the length of the first line segment of the dotted line is 5-2 let a: CGFloat = 5 let B: CGFloat = 1 let lengths = [a, B] contextRef ?. SetLineDash (phase: 2, lengths: lengths) path. move (to: CGPoint (x: 5, y: 20) path. addLine (to: CGPoint (x: 100, y: 100) // 3. add to image context contextRef ?. AddPath (path) // 4. Set the graphical context state attribute contextRef ?. SetStrokeColor (UIColor. red. cgColor) // The border color contextRef ?. SetFillColor (UIColor. blue. cgColor) // fill color. You can use contextRef in a closed path ?. SetLineWidth (2) // line width // 5. Draw contextRef ?. StrokePath ()}
Closed Graph Drawing

The above drawing method seems a little troublesome. In fact, Core Graphics encapsulates the two steps of creating a path object and adding it to the context, which can be completed in one step, next we will draw a simple rectangle with a line segment:

// 1. Get the image context let contextRef = UIGraphicsGetCurrentContext () // 2. Start to draw a square contextRef ?. Move (to: CGPoint (x: 10, y: 10) contextRef ?. AddLine (to: CGPoint (x: 110, y: 10) contextRef ?. AddLine (to: CGPoint (x: 110, y: 110) contextRef ?. AddLine (to: CGPoint (x: 10, y: 110) // we can use this method to plot contextRef directly ?. ClosePath () // 3. Set the related status contextRef ?. SetLineWidth (2) contextRef ?. SetStrokeColor (UIColor. red. cgColor) contextRef ?. SetFillColor (UIColor. blue. cgColor) // 4. Start to draw. Both border (PATH) and contextRef ?. DrawPath (using:. fillStroke)
Draw a rectangle

The above code has been relatively simplified. In addition to the path, the rectangle and the ellipse have corresponding plotting methods.

// ----------- Use addRect to draw ------------ // 1. Obtain the image context let contextRef = UIGraphicsGetCurrentContext () // 2. Path contextRef ?. AddRect (CGRect (x: 10, y: 10, width: 100, height: 100) // 3. Status contextRef ?. SetFillColor (UIColor. blue. cgColor) contextRef ?. SetStrokeColor (UIColor. red. cgColor) // 4. Draw contextRef ?. DrawPath (using:. fillStroke)

  

// ----------- Use the UI method to draw ------------ // draw a rectangle with a fill color of red. red. setFill () UIRectFill (CGRect (x: 10, y: 10, width: 100, height: 100) // draw a rectangle UIColor with a blue border. blue. setStroke () UIRectFrame (CGRect (x: 20, y: 20, width: 100, height: 100 ))
Draw a circle
// 1. obtain the graphic context let contextRef = UIGraphicsGetCurrentContext () // 2. specify a rectangle let rect = CGRect (x: 10, y: 10, width: 100, height: 100) // 3. add contextRef ?. AddEllipse (in: rect) // incircle // 4. Set the fill color contextRef ?. SetFillColor (UIColor. red. cgColor) // 5. Draw contextRef ?. DrawPath (using:. fill)
Draw an arc
// 1. Obtain the graphic context let contextRef = UIGraphicsGetCurrentContext () // 2. Add the radian let center = CGPoint (x: 100, y: 100) // center Coordinate
ContextRef. moveTo (center) // Add this code to draw a sector let radius: CGFloat = 50 // radius let startAngle: CGFloat = 0 // start radian let endAngle: CGFloat = CGFloat (Double. pi/4) // end-radian let clockwise = true // Do You Want To counter-clockwise contextRef ?. AddArc (center: center, radius: CGFloat (radius), startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) // 3. Set the fill color contextRef ?. SetFillColor (UIColor. red. cgColor) // 4. Draw contextRef ?. DrawPath (using:. fill)

  

 

Gradient Filling

In the Demo above, we can see how to set the fill color. In fact, many times the solid color filling does not meet our football requirements, for example, you may need to set a beautiful background for drawing some images. If the ui mm does not cut the image, you may choose the gradient filling mode.

Z 2D gradient methods are divided into two types:

A. Linear Gradient line: gradient gradually changes from the starting position to the ending position in a straight line.

B. Radial Gradient: Focus on the center point from the starting gradient to the surrounding radiation, until the end of the gradient.

To make a gradient, you must first set the gradient color from the start position to the end position. ui mm can be set to no stranger to the gradient settings, you only need to specify different colors at the specified position, the rest can be handled by the system. For example, three colors are specified at the starting position, 3/10, and ending position to form a gradient composed of three colors.

In addition, you need to specify the color space to draw the gradient in iOS. The color space is the process in which different colors take values in different dimensions to form a color. For RGB, if Red, green, and blue are regarded as x, y, and Z coordinate systems, then, in the three coordinates, different values in the range of 0 to can be used to form various colors. Of course, the coordinates of different color spaces are also different, that is to say, the color representation is different. In addition to RGB, commonly used color spaces include CMYK (commonly used in printing) and Gray.

In addition to the conventional method (for exampleCGContextSetRGBFillColor (CGContextRef context, CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)Method) in addition to setting RGB and opacity, sometimes the color parameter is an array. For exampleCGContextSetFillColor (CGContextRef context, const CGFloat * components)In this case, how to store colors in the components array depends on the color space. If the color space uses RGB, the four elements in the array are in one group, they are red, green, blue, and alpha. If CMYK color space is used, the Five Elements in the array are a group of cyan, magenta, yellow, black, and alpha.

The following two gradient methods are used:

1. Linear Gradient

Override func draw (_ rect: CGRect) {// obtain the context let contextRef = UIGraphicsGetCurrentContext () // use the RGB color space let colorSpace = CGColorSpaceCreateDeviceRGB () // specify the gradient/* colorSpace: color Space colorComponents: color array. Because it is specified as an RGB color space, the four array elements represent a color (red \ green \ blue \ alpha). If there are three colors, the array must contain 3*4 elements. Locations: The color location is 0-1. the number of this array is not less than the number of colors count: the number of gradient, equal to the count */let colorComponents of locations: [CGFloat] = [248.0/255.0, 86.0/255.0, 86.0/255.0, 1,249.0/255.0, 127.0/255.0, 127.0/255.0, 1, 1.0, 1.0, 1.0, 1.0] let locations: [CGFloat] = [0, 0.3, 1.0] let gradient = CGGradient (colorSpace: colorSpace, colorComponents: colorComponents, locations: locations, count: 3) // draw a linear color gradient/* start: start coordinate end: end Coordinate Options: painting method. The painting is performed before the start position of kCGGradientDrawsBeforeStartLocation. The painting is not performed after the end position. The painting is not performed before the start position of kCGGradientDrawsAfterEndLocation. Fill in the painting after the end point ?. DrawLinearGradient (gradient !, Start: CGPoint (x: 0, y: 20), end: CGPoint (x: 0, y: self. frame. size. height-40), options:. drawsBeforeStartLocation )}

2. Radial Gradient

Override func draw (_ rect: CGRect) {// obtain the context let contextRef = UIGraphicsGetCurrentContext () // use the RGB color space let colorSpace = CGColorSpaceCreateDeviceRGB () // specify the gradient/* colorSpace: color Space colorComponents: color array. Because it is specified as an RGB color space, the four array elements represent a color (red \ green \ blue \ alpha). If there are three colors, the array must contain 3*4 elements. Locations: The color location is 0-1. the number of this array is not less than the number of colors count: the number of gradient, equal to the count */let colorComponents of locations: [CGFloat] = [248.0/255.0, 86.0/255.0, 86.0/255.0, 1,249.0/255.0, 127.0/255.0, 127.0/255.0, 1, 1.0, 1.0, 1.0, 1.0] let locations: [CGFloat] = [0, 0.3, 1.0] let gradient = CGGradient (colorSpace: colorSpace, colorComponents: colorComponents, locations: locations, count: 3) /* draw a radial gradient context: Graph context gradient: gradient sta RtCenter: start point position startRadius: Start radius (usually 0, otherwise there is no fill in the content in this radius range) endCenter: End Point Location (usually the same as the start point, otherwise there will be an offset) endRadius: endpoint radius (that is, the diffusion length of the gradient) options: Draw method, draw before the start position of kCGGradientDrawsBeforeStartLocation, but do not draw after the end position, do not draw before the start position of kCGGradientDrawsAfterEndLocation, however, after the end point, fill in */let center = CGPoint (x: self. frame. size. width/2, y: self. frame. size. height/2) contextRef ?. DrawRadialGradient (gradient !, StartCenter: center, startRadius: 0, endCenter: center, endRadius: 30, options:. drawsAfterEndLocation )}

3. Gradient Filling

The above is just to draw a gradient to the graphic context. In actual development, sometimes we need to fill in the corresponding gradient. For example, if we have drawn a rectangle, how can we fill it with gradient? You can use gradient cropping here (of course, it is more convenient to use layer CALayer). In particular, the area cropping is not only applicable to gradient filling, but also to other graphics, note that only rectangular cropping is allowed.

Override func draw (_ rect: CGRect) {// obtain the context let contextRef = UIGraphicsGetCurrentContext () // use the RGB color space let colorSpace = CGColorSpaceCreateDeviceRGB () // You can also use the UIRectClip (CGRect (x: 0, y: 20, width: self. frame. size. width, height: self. frame. size. height-40) // specify gradient/* colorSpace: Color Space colorComponents: color array, because it is specified as an RGB color space, the four array elements represent a color (red \ green \ blue \ alpha). If there are three colors, there must be 3 * Four elements. Locations: The color location is 0-1. the number of this array is not less than the number of colors count: the number of gradient, equal to the count */let colorComponents of locations: [CGFloat] = [248.0/255.0, 86.0/255.0, 86.0/255.0, 1,249.0/255.0, 127.0/255.0, 127.0/255.0, 1, 1.0, 1.0, 1.0, 1.0] let locations: [CGFloat] = [0, 0.3, 1.0] let gradient = CGGradient (colorSpace: colorSpace, colorComponents: colorComponents, locations: locations, count: 3) // draw a linear color gradient/* start: start coordinate end: end Coordinate Options: painting method. The painting is performed before the start position of kCGGradientDrawsBeforeStartLocation. The painting is not performed after the end position. The painting is not performed before the start position of kCGGradientDrawsAfterEndLocation. Fill in the painting after the end point ?. DrawLinearGradient (gradient !, Start: CGPoint (x: 0, y: 20), end: CGPoint (x: 0, y: self. frame. size. height-40), options:. drawsBeforeStartLocation )}

  

 

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.