"IOS" uses coretext to achieve picture-and-text blending

Source: Internet
Author: User

iOS does not have out-of-the-box support for text-to-graphic controls, and it is hard to make complex typography with multiple base controls combined into a mix of graphics and text. The solution for this is to use Coretext to draw, or use Textkit. This article mainly explains the use of Coretext.

Case

Https://github.com/ClavisJ/CoreTextDemo

Environmental information:

Mac OS X 10.10.1

Xcode 6.1.1

IOS 8.1

Text: First, Core text introduction

Coretext is a text frame based on IOS3.2 and OSX10.5 for fine text typesetting. It interacts directly with the core Graphics (AKA: Quartz), passing the text content, position, font, and glyph that need to be displayed directly to Quartz, rendering it more efficient than other UI components.

Core Text Frame composition

Comparison of the advantages and disadvantages of coretext and UIWebView in typesetting

UIWebView is also often used to handle complex typesetting, and the corresponding layout between them is as follows (excerpt from "Advanced iOS Development"-Tang Qi):

  • Coretext consumes less content and renders more quickly. UIWebView consumes more memory and renders slowly.
  • Coretext can get the height of the display exactly before rendering the interface (as long as Ctframe is available), and WebView can get the height of the content only after rendering the content (and it needs to be obtained with JavaScript code).
  • Coretext Ctframe can be rendered in a background thread, and UIWebView content is only rendered on the main thread (UI thread).
  • Based on the Coretext can do better native interaction effect, interactive effect can be more delicate. and the interactive effect of UIWebView is implemented by JavaScript, there will be some lag in the interactive effect. For example, under UIWebView, a simple button-down operation does not make the immediate and fine-pressed effect of the native button.

Disadvantages of Coretext typesetting:

  • Coretext rendered content is not as easy as UIWebView to support content replication.
  • Based on the coretext to the layout of the need to handle a lot of replication logic, such as the need to handle the picture and the text mix related logic, but also need to implement the connection click Operation Support.

There are many applications in the industry using Coretext technology for typesetting, such as Sina Weibo client, read more reading client, ape Question bank and so on.

Third, Draw plain text

We create a class that inherits from UIView, overriding his DrawRect method to draw plain text.

- (void) DrawRect: (CGRect) Rect {[Super Drawrect:rect];Step 1: Get the context currently used to draw the canvas for subsequent drawing of the content on the canvasBecause the core text is used in conjunction with the core Graphic, like Core Graphic, the drawing needs to be drawn with the current context.Cgcontextref context =Uigraphicsgetcurrentcontext ();Step 2: Flip the current coordinate system (because the lower-left corner of the screen is (0,0) for the underlying drawing engine)Cgcontextsettextmatrix (Context,cgaffinetransformidentity);CGCONTEXTTRANSLATECTM (Context,0,Self.bounds.size.height);CGCONTEXTSCALECTM (Context,1.0,-1.0);Step 3: Create a drawing areaCgmutablepathref Path =Cgpathcreatemutable ();Cgpathaddellipseinrect (Path,NullSelf.bounds);Step 4: Create the text you want to draw and calculate the area you want to drawnsmutableattributedstring *attrstring = [[Nsmutableattributedstring Alloc] Initwithstring:@ "iOS program will create a main thread on startup, and only one thing on a thread, if you perform some time-consuming operations on the main threads, such as loading a network picture, downloading a resource file, etc. will block the main thread (causing the interface to die and not interact), so you need to use multithreading techniques to avoid such situations. iOS has three kinds of multithreading technology NSTHREAD,NSOPERATION,GCD, these three technologies are introduced with the development of iOS, the abstraction level from low to high, the use is more and more simple. "]; //Step 5: Generate Ctframesetterref ctframesetterref framesetter = based on attributedstring Ctframesettercreatewithattributedstring ((cfattributedstringref) attrstring); Ctframeref frame = Ctframesettercreateframe (Framesetter, Cfrangemake (0, [attrstring length]), path, NULL); //Step 6: Draw Ctframedraw (frame, context); //Step 7. Memory Management Cfrelease (frame); cfrelease (path); cfrelease (framesetter);}          

The effect of running is as

Coretext Drawing Plain Text

Iv. about the coordinate system

Step 2 of the appeal Code deals with the coordinate system of the drawing, because in iOS uikit, the UIView is the origin of the upper-left corner, and the core text is initially positioned to use the typesetting system with the desktop application, and the desktop application's coordinates are in the lower-left corner as the origin, which is the core Text is drawn in the lower left-hand corner when it is drawn, so the current coordinate system needs to be processed.

In fact, the context in core Graphic is also the origin of the lower left corner, but why we do not need to process the coordinate system when we draw some simple graphics with the core Graphic because this method Uigraphicsgetcurrentcontext () to obtain the current context is already processed, use the following method to view the specified context of the current graphics state transformation matrix.

NSLog(@"当前context的变换矩阵 %@", NSStringFromCGAffineTransform(CGContextGetCTM(context)));

The printed result is [2, 0, 0,-2, 0, 654], which can be found to be different from the value of the cgaffinetransformidentity [1, 0, 0, 1, 0, 0] , and whether the device is RET The INA screen is related to the device size. His role is to flip the context-space coordinate system and make the original left-hand corner The origin point in the upper-right corner, and turn the positive y-axis upward to the positive y-axis. So when using DrawRect, the current context has been made a flip, if not the current coordinate system processing, you will find that the text is drawn up upside down,

Do not process context

So we need to reset the current coordinate system rollover state, after a flip, the matrix after processing is [2, 0,-0, 2, 0, 0], function CGCONTEXTTRANSLATECTM the role of the transformation coordinate system in the origin, function The role of CGCONTEXTSCALECTM is to change the scale of the user coordinate system.

Five, custom text color, font and line spacing

You can see that we use the Nsmutableattributedstring class to describe the text that needs to be drawn, and a Nsmutableattributedstring object can contain many properties, each of which has a corresponding character area, We can use these attributes to describe special colors and fonts in the text.

- (void) DrawRect: (CGRect) Rect {Omit the previous step 1-4Step 8: Set part of the text color [attrstring addattribute: (ID) kctforegroundcolorattributename value:[Uicolor Greencolor] Range:Nsmakerange (10,10)];Set some textCGFloat fontSize =20; Ctfontref fontref = Ctfontcreatewithname ((CFSTRINGREF)@ "ARIALMT", FontSize,NULL); [Attrstring AddAttribute: (ID) kctfontattributename Value: (__bridgeID) fontref Range:Nsmakerange (15,10)];Cfrelease (FONTREF);Set line spacingCGFloat linespacing =10;ConstCfindex knumberofsettings =3; Ctparagraphstylesetting Thesettings[knumberofsettings] = {{kctparagraphstylespecifierlinespacingadjustment,sizeof (cgfloat), &linespacing}, {kctparagraphstylespecifiermaximumlinespacing, sizeof (cgfloat ), &linespacing}, {kctparagraphstylespecifierminimumlinespacing, sizeof (cgfloat), &linespacing}}; Ctparagraphstyleref theparagraphref = ctparagraphstylecreate (thesettings, knumberofsettings); [Attrstring AddAttribute: (ID) kctparagraphstyleattributename value: (__bridge ID) theparagraphref range:  Nsmakerange (0, attrstring.length)]; cfrelease (THEPARAGRAPHREF); //Omit step after 5-7}           
The final effect is as follows

Custom Text Properties

Tip: When configuring nsmutableattributedstringattribute, use a lot of this (__bridge? ID) to explain the following: This is because AddAttribute: is the OC method, requires object C object, and ctparagraphstyleref These are the C language implementation of the core Foundation Framework The objects in the framework, which can be transformed and manipulated by each other. Objects in the Core Foundation Framework framework also have the concept of reference counting, but instead of release/retain in the cocoa framework, they use their own cfretain/cfrelease interfaces. In the use of the time to pay more attention to the issue of reference and release, a more detailed explanation can refer to this article.

Six, picture and text mixed row

Finally to start the picture mixed, above said so much, we have to carry on a summary, is coretext draw the flowchart and the relationship between Ctframe and Ctline,ctrun:

Coretext drawn flowchart, relationship between Ctframe and Ctline Ctrun

Let's explain these classes:

Cfattributedstringref: Property string for storing text characters and character attributes that need to be drawn

Ctframesetterref: Initialized by Cfattributedstringref, as a production plant for Ctframe objects, responsible for creating corresponding ctframe based on path

Ctframe: The class used to draw the text, which can be drawn directly to the context through the Ctframedraw function

Ctline: Inside Ctframe is composed of multiple ctline, each ctline represents a row

Ctrun: Each ctline is made up of multiple ctrun, each of which represents a set of text that shows consistent style

In fact Coretext does not directly support the drawing of the picture, but we can first where the need to display the picture with a special blank placeholder, and set the font's ctrundelegate information for the image to be displayed width and height, When you draw the text, you will leave the position of the picture first, and then draw the picture with Cgcontextdrawimage in the DrawRect method.

- (void) DrawRect: (CGRect) Rect {[Super Drawrect:rect];Omit step 1-4, step 8Step 9: Picture-and-Text blending sectionsCtrundelegatecallbacks: A structure for holding pointers, Ctrun delegate for callback Ctrundelegatecallbacks callbacks; memset (&callbacks,0,sizeof (ctrundelegatecallbacks)); Callbacks.version = KCTRunDelegateVersion1; Callbacks.getascent = Ascentcallback; Callbacks.getdescent = Descentcallback; Callbacks.getwidth = Widthcallback;Picture Information DictionaryNsdictionary *imginfodic = @{@ "width": @100,@ "height": @30};Set Ctrun proxy Ctrundelegateref delegate = Ctrundelegatecreate (&callbacks, __bridgevoid *) imginfodic);Use 0xFFFC as a placeholder for whitespaceUnichar Objectreplacementchar =0xFFFC;NSString *content = [NSString Stringwithcharacters:&objectreplacementchar Length:1];nsmutableattributedstring *space = [[Nsmutableattributedstring alloc] initwithstring:content];Cfattributedstringsetattribute ((CFMUTABLEATTRIBUTEDSTRINGREF) space,Cfrangemake (0,1), Kctrundelegateattributename, delegate);Cfrelease (delegate);Inserts the created blank attributedstring into the current attrstring, the location can be arbitrarily specified, cannot cross the border [attrstring insertattributedstring:space Atindex:50];Omit Step 5-6Step 10: Draw the pictureUIImage *image = [UIImage imagenamed:@ "Coretext-img-1.png"];Cgcontextdrawimage (Context, [Self calculateimagepositioninctframe:frame], image. Cgimage);Omit Step 7}#pragma Mark-ctrun Delegate callback methodStaticCGFloat Ascentcallback (void *ref) {return [(NSNumber *) [(__bridgeNsdictionary *) ref Objectforkey:@ "height"] floatvalue]; }StaticCGFloat Descentcallback (void *ref) {Return0; }StaticCGFloat Widthcallback (void *ref) {return [(NSNumber *) [(__bridgeNsdictionary *) ref Objectforkey:@ "width"] floatvalue]; }/** * Gets the area of the drawing picture according to Ctframeref * * @param ctframe Ctframeref Object * * @return the area where the picture is drawn */-(CGRect) Calculateimagepositioninctframe: (ctframeref) Ctframe {Get Ctline ArrayNsarray *lines = (Nsarray *) Ctframegetlines (ctframe);Nsinteger LineCount = [lines count];Cgpoint Lineorigins[linecount]; Ctframegetlineorigins (Ctframe,Cfrangemake (0,0), lineorigins);Traverse each Ctlinefor (Nsinteger i =0; i < LineCount; i++) {Ctlineref line = (__bridge ctlineref) lines[i];Nsarray *runobjarray = (Nsarray *) ctlinegetglyphruns (line);Traverse the Ctrun in each ctlinefor (ID runobjIn Runobjarray) {ctrunref run = (__bridge ctrunref) runobj;Nsdictionary *runattributes = (Nsdictionary *) ctrungetattributes (run); Ctrundelegateref delegate = (__bridge ctrundelegateref) [Runattributes Valueforkey: (ID) Kctrundelegateattributename];if (delegate = =Nil) {Continue }Nsdictionary *metadic = Ctrundelegategetrefcon (delegate);if (![ Metadic iskindofclass:[Nsdictionary class]]) {Continue }CGRect runbounds;CGFloat ascent;CGFloat descent; RunBounds.size.width = Ctrungettypographicbounds (Run,Cfrangemake (0, 0), &ascent, &descent,  NULL); RunBounds.size.height = ascent + descent; cgfloat xoffset = Ctlinegetoffsetforstringindex (line, Ctrungetstringrange (run). Location, null); runbounds.origin.x = lineorigins[i].x + xoffset; RUNBOUNDS.ORIGIN.Y = LINEORIGINS[I].Y; RUNBOUNDS.ORIGIN.Y-= descent; cgpathref pathref = Ctframegetpath (ctframe); cgrect colrect = cgpathgetboundingbox (PATHREF); cgrect delegatebounds = cgrectoffset (Runbounds, colRect.origin.x, COLRECT.ORIGIN.Y); return delegatebounds;} } return cgrectzero;}               
At this point we completed the use of Coretext for text-to-picture mixed, the above to get the image location of the method can only get the first picture location, you can self-improvement, with an array to store the picture drawing area. Tang Qi in the "iOS Development Advanced" book more about the Coretext package, interested can see.

Resources:

http://geeklu.com/2013/03/core-text/

Http://xiangwangfeng.com/2014/03/06/iOS%E6%96%87%E5%AD%97%E6%8E%92%E7%89%88 (Coretext)%e9%82%a3%e4%ba%9b%e4%ba% 8b/

http://blog.devtang.com/blog/2013/10/21/the-tech-detail-of-ape-client-3/

http://www.yifeiyang.net/development-of-the-iphone-simply-6/

"IOS" uses coretext to achieve picture-and-text blending

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.