How is iOS & quot; Painting & quot?

Source: Internet
Author: User
Tags drawtext

What is a drawing engine?

If you are engaged in graphics/interface development or game development on other platforms, you must know that no matter how the upper-layer UI is presented and responded, there must be a drawing engine at the bottom layer. iOS is no exception. this article describes the usage and related knowledge of iOS Graphics in detail, hoping to help you with Coding.

  • Blog: http://www.cnblogs.com/jhzhu
  • Email: jhzhuustc@gmail.com
  • Author: Zhi Ming-so
  • Time:

^ This blog needsCALayerAndUIViewHave a basic understanding. Refer to the blog to talk about iOS Animation.

What is a drawing engine?

The drawing engine, in general, is like giving you a pen and several colors of paint, you can use it to makeBasic.
OneBasic Drawing EngineIncludes the following interfaces:

// Code-1I1. drawLine () // draw any line and color the line. i2. drawPath () // draw the shape based on the path and support filling color. i3. drawImage () // draw an image (e.g. xxx.jpg, xxx.png) I4. drawGradient () // draw the gradient fill I5. transform () // matrix ing transformation. i6. drawText () // draw text

It's hard to imagine that with the above interfaces, we canConvenientTo draw any desired image.
Here we emphasize thatConvenient, Some interfaces are notRequiredFor exampledrawImage(), We can always call a limited number of timesdrawLine()AnddrawShape()To draw any given Image, but the complexity can be imagined.
A drawing engine is designed to facilitate upper-layer calls, so it encapsulates someMost commonAndBasicThe preceding five interfaces meet one of the two conditions.Most commonAndBasicThere is no clear definition, so different drawing engines may have some common interfaces, but they are similar.



IOS graphics engine

Next we willCode-1The interface mentioned in is introduced on the iOS platform.

Where to draw?

If we create a newUIViewClass, we will get the following code:

//Code-2#import "GraphicsViewControllerView.h"@implementation GraphicsViewControllerView- (id)initWithFrame:(CGRect)frame{     self = [super initWithFrame:frame];     if (self) {        // Initialization code }    return self; }- (void)drawRect:(CGRect)rect{    // Drawing code }@end

Generally,drawRect()BecauseUIViewAddsubViewOr setUIViewRelated attributes (e.g.backgroundCrolor,UIKitThe meanings of these parameters are automatically drawnCALayerIn other words, we generally do not need to draw it by ourselves,UIKitWill automatically help us complete the drawing.
However, if you do not addsubView, Not setUIViewYou can usedrawRect()To manually draw the image.

Context

A graphical context can be thought of as a canvas, offering an enormous number of properties such as pen color, pen thickness, etc. given the context, you can start painting straight away inside the drawRect: method, and Cocoa Touch will make sure that the attributes and properties of the context are applied to your drawings. we will talk about this more later, but now, let's move on to more interesting subjects.

DrawText

CreateUIViewClassCustomUIView, As follows:drawRect()Method.
NewCustomUIViewObject. If no attribute is set, add it to the display list.

//Code-3- (void)drawRect:(CGRect)rect{     UIFont *font = [UIFont systemFontWithSize:40.f];     NSString *myString = @"Some String";    [myString drawAtPoint:CGPointMake(40, 180) withFont:font];}

Run, we can see that we have not added anyUITextFieldThe text is displayed ~

More:

There are also ways to draw textdrawInRect:withFont:For more information, see the official documentation.

SetColor

We setCode-3Add two lines of code in:

//Code-4- (void)drawRect:(CGRect)rect{     UIColor* color = [UIColor blueColor];       //create color    [color set];                                //set color    UIFont *font = [UIFont systemFontWithSize:40.f];     NSString *myString = @"Some String";    [myString drawAtPoint:CGPointMake(40, 180) withFont:font];}

The text is changed from black to blue.

More:

UIColorThere are two other methodssetStrokeAndsetFillSet the line color and fill color respectively, which will be used in later sections.setThe method affects all foreground views.

DrawImage

Similarly, rewrite the following:drawRectMethod:

//Code-5- (void)drawRect:(CGRect)rect{     /* Assuming the image is in your app bundle and we can load it */    UIImage *xcodeIcon = [UIImage imageNamed:@"filename.png"];    [xcodeIcon drawAtPoint:CGPointMake(0.0f, 20.0f)];}

We can see that the image is drawn.

More:

UIImageThere are other ways to draw:

drawInRect:drawAsPatternInRect:drawAtPoint:blendMode:alpha:drawInRect:blendMode:alpha:

The method name clearly describes the purpose of the method. For details, refer to the official documentation.

DrawLine

These two are the most basic in the drawing engine, so they are put together for discussion.

// Code-6: drawLine-(void) drawRect :( CGRect) rect {/* Step1 set the drawing color */[[UIColor brownColor] set]; /* Step 2 get the current canvas: Graphic Context */CGContextRef currentContext = UIGraphicsGetCurrentContext ();/* Step 3 set the line width */CGContextSetLineWidth (currentContext, 5.0f ); /* Step 4 move the paint brush to the starting point */CGContextMoveToPoint (currentContext, 50366f, 10.0f);/* Step 5 draw a line from the starting point to the ending point */CGContextAddLineToPoint (currentContext, 100366f, 200366f ); /* Step 6 submit and draw */CGContextStrokePath (currentContext );}

If you want to draw multiple lines consecutively, you canCode-6InStep5AndStep6Multiple callsCGContextAddLineToPoint().

More:

CGContextSetLineJoinYou can change the style of the line intersection.

DrawPath

If we want to quickly draw a line, calldrawLineIt seems a little bloated.drawPath, It isdrawLineEnhanced version.
drawPathThe general steps are as follows:

// Code-7: drawPath-(void) drawRect :( CGRect) rect {/* Step1 get the current canvas: Graphic Context */CGContextRef currentContext = UIGraphicsGetCurrentContext (); /* Step 2 create path */CGMutablePathRef path = CGPathCreateMutable ();/* Step 3 move to the start point */CGPathMoveToPoint (path, NULL, screenBounds. size. width, screenBounds. origin. y);/* Step 4 draw an elliptic */CGPathAddEllipseInRect (path, & CGAffineTransformIdentity, CGRectMake (0,320,320,160);/* Step 5 add another line */CGPathAddLineToPoint (path, NULL, screenBounds. origin. x, screenBounds. size. height);/* Step 6 Add path */CGContextAddPath (currentcontext, path) to the canvas;/* Step 7 set the painting type: kCGPathStroke (draw edge), kCGPathFill (fill the area in the path ), kCGPathFillStroke (including the first two items) */CGContextDrawPath (currentcontext, kCGPathFillStroke);/* Step 8 submit the painting */CGContextStrokePath (currentContext ); /* Step9 release path */CGPathRelease (path );}
More:

Interface for drawing common geometric images:CGPathAddCurveToPoint,CGPathAddArcToPoint,CGPathAddRectAnd so on...

Transform

In iOStransformUseCGAffineTransformYou can use a matrix to construct any two-dimensional transformation:

/*a: The value at position [1,1] in the matrix.b: The value at position [1,2] in the matrix.c: The value at position [2,1] in the matrix.d: The value at position [2,2] in the matrix.tx: The value at position [3,1] in the matrix.ty: The value at position [3,2] in the matrix.*/CGAffineTransformMake(CGFloat a, CGFloat b, CGFloat c, CGFloat d, CGFloat tx, CGFloat ty)

Matrix Representation:

IOS also provides quick building methods for common transformations:

CGAffineTransformIdentity // unit matrix without any transformation CGAffineTransformMakeRotation // rotate CGAffineTransformMakeScale // scale CGAffineTransformMakeTranslation // Translation

InCode-7 Step4, DrawpathThe unit matrix is used.CGAffineTransformIdentity, Indicating that no transformation is performed. NormallytransformPassed as a parameter.CGPathAddCurveToPoint,CGPathAddArcToPoint,CGPathAddRectEach function hastransformParameters.



IOS plotting application in projects

Generally, we only needUIViewAddsubView,UIKitThe image will be automatically drawn for us. However, you may need to manually draw the image in the following cases:

 

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.