iOS Reader Practice Series (i) Coretext Plain text typesetting basics

Source: Internet
Author: User

Preface: Before doing the company reading the app, recently had time to write a reading part of the realization process, for carding logic, the plan will write a series of hope to relate to as many aspects and details, welcome everyone to communicate, spit groove, shoot bricks, common progress.

The typesetting of reading is Coretext, this introduction uses the Coretext to realize the basic typesetting function.

About the implementation of the principle of coretext, you can view the document or other materials, this is not described here, only how to apply the Coretext to achieve a simple text typesetting function.

Because Coretext is out-of-screen, the content is finished before the content is rendered to the screen.

The process of typesetting is generally divided into steps:

First, the property string is obtained by the original text data and the related configuration needed.

Second, get ctframesetter by property string

Third, by the Ctframesetter and drawing area to get Ctframe

Finally, the ctframe is rendered into the context of the view

1. Get the attribute string from the original text data and the related configuration needed

The key to this is to get the configuration, which may include text alignment, paragraph wrapping indentation, High Line, and some related configuration properties:

@interfaceCtframeparserconfigure:nsobject@property (nonatomic, assign) CGFloat framewidth; @property (nonatomic, assign) CGFloat frameheight;//Font Properties@property (nonatomic, assign) CGFloat wordspace; @property (nonatomic, strong) Uicolor*TextColor, @property (nonatomic, strong) NSString*fontname; @property (nonatomic, assign) cgfloat fontSize;//Paragraph Properties@property (nonatomic, assign) CGFloat linespace; @property (nonatomic, assign) cttextalignment textalignment;//Text alignment mode@property (nonatomic, assign) CGFloat firstlineheadindent;//paragraph first line indent@property (nonatomic, assign) CGFloat headindent;//Integral indent on left of segment@property (nonatomic, assign) CGFloat tailindent;//segment End Indent@property (nonatomic, assign) Ctlinebreakmode Linebreakmode;//line break mode@property (nonatomic, assign) CGFloat lineheightmutiple;//Line Multiplier (its value indicates a multiple of the original row height)@property (nonatomic, assign) CGFloat maxlineheight;//Maximum row height limit (0 means unrestricted, non-negative, row height cannot exceed this value)@property (nonatomic, assign) CGFloat minlineheight;//Minimum line height limit@property (nonatomic,assign) cgfloat paragraphbeforespace;//spacing before paragraph (relative to last paragraph plus spacing)@property (nonatomic, assign) CGFloat paragraphafterspace;//End spacing (relative to the next paragraph plus the spacing)@property (nonatomic, assign) ctwritingdirection writedirection; //Writing Direction@property (nonatomic, assign) CGFloat linespacingadjustment; //The space in points added between lines within the paragraph (commonly known as leading).@end

Next we will use these properties to generate the configuration we need, and after we assign values to these properties according to our needs, we will use the following method to get the configuration we need:

//returns a collection of all properties of the text (in dictionary form), including fonts, paragraphs, etc.-(Nsdictionary *) Attributeswithconfig: (Ctframeparserconfigure *) config{//Paragraph PropertiesCGFloat linespacing =Config.linespace; CGFloat firstlineindent=config.firstlineheadindent; CGFloat lineindent=config.headindent; CGFloat tailindent=config.tailindent; Ctlinebreakmode Linebreakmode=Config.linebreakmode; CGFloat lineheightmutiple=config.lineheightmutiple; CGFloat Paragraphbeforespace=Config.paragraphbeforespace; CGFloat Paragraphafterspace=Config.paragraphafterspace; Ctwritingdirection Writedirect=config.writedirection; Cttextalignment TextAlignment=config.textalignment; ConstCfindex knumberofsettings = -; Ctparagraphstylesetting Paragraphsettings[knumberofsettings]={{kctparagraphstylespecifierlinespacingadjustment,sizeof(CGFloat), &linespacing}, {kctparagraphstylespecifiermaximumlinespacing,sizeof(CGFloat), &linespacing}, {kctparagraphstylespecifierminimumlinespacing,sizeof(CGFloat), &linespacing}, {kctparagraphstylespecifieralignment,sizeof(TextAlignment), &TextAlignment}, {kctparagraphstylespecifierfirstlineheadindent,sizeof(FirstLineIndent), &FirstLineIndent}, {kctparagraphstylespecifierheadindent,sizeof(Lineindent), &Lineindent}, {kctparagraphstylespecifiertailindent,sizeof(Tailindent), &Tailindent}, {kctparagraphstylespecifierlinebreakmode,sizeof(Linebreakmode), &Linebreakmode}, {kctparagraphstylespecifierlineheightmultiple,sizeof(Lineheightmutiple), &Lineheightmutiple}, {kctparagraphstylespecifierlinespacing,sizeof(Lineheightmutiple), &Lineheightmutiple}, {kctparagraphstylespecifierparagraphspacingbefore,sizeof(Paragraphbeforespace), &Paragraphbeforespace}, {kctparagraphstylespecifierparagraphspacing,sizeof(Paragraphafterspace), &Paragraphafterspace}, {kctparagraphstylespecifierbasewritingdirection,sizeof(Writedirect), &writedirect},}; Ctparagraphstyleref Theparagraphref=ctparagraphstylecreate (paragraphsettings, knumberofsettings); /** * Font Properties*/cgfloat fontSize=config.fontsize; //Use of the postname after iOS10//ctfontref fontref = Ctfontcreatewithname ((cfstringref) Config.fontname, fontSize, NULL);Ctfontref Fontref =ctfontcreatewithname (NULL, fontSize, NULL);//ctfontref fontref = Ctfontcreatewithname ((cfstringref) @ "Timesnewromanpsmt", FontSize, NULL);Uicolor* TextColor =Config.textcolor; //Set Font spacing    LongNumber =Config.wordspace; Cfnumberref Num= Cfnumbercreate (Kcfallocatordefault, Kcfnumbersint8type, &Number ); Nsmutabledictionary* Dict =[Nsmutabledictionary dictionary]; dict[(ID) Kctforegroundcolorattributename] = (ID) Textcolor.cgcolor; dict[(ID) Kctfontattributename] = (__bridgeID) Fontref; dict[(ID) Kctkernattributename] = (__bridgeID) num; dict[(ID) Kctparagraphstyleattributename] = (__bridgeID) Theparagraphref;    Cfrelease (num);    Cfrelease (THEPARAGRAPHREF);    Cfrelease (FONTREF); returndict;}

The preceding procedure generates paragraph attributes based on the paragraph attribute values provided above, then generates attributes such as font, font spacing, and font color, and then sequentially stores them in the dictionary.

It is important to note that ctparagraphstylesetting is a C-language array, and you need to specify the number of array elements at creation time.

Objects created in the Corefoundation library need to be released manually (most of the objects generated by the Create method)

In addition, after the system upgrade to iOS10, in the adjustment font size re-typesetting, became very slow, with instrument looked up, found

Ctfontref fontref = Ctfontcreatewithname ((cfstringref) Config.fontname, fontSize, NULL);

This code execution time is very long, find data discovery is caused by the font, IOS10 need to use the corresponding post NAME.

2. Get Ctframesetter by property string

// Creating an Ctframesetterref instance    Ctframesetterref Framesetter = ctframesettercreatewithattributedstring ((cfattributedstringref) mabStr);

3. Get Ctframe by Ctframesetter and drawing area

The key to this step is to get the area drawn:

// Get the height    of the area you want to draw Cgsize restrictsize = cgsizemake (viewwidth, Cgfloat_max);     = Ctframesettersuggestframesizewithconstraints (Framesetter, Cfrangemake (0,0), nil, Restrictsize, nil);     = Coretextsize.height;

Then generate Ctframe:

// Generate drawn Area + (ctframeref) Createframewithframesetter: (ctframesetterref) Framesetter framewidth: (cgfloat) Framewidth Stringrange: (cfrange) Stringrange orginy: (cgfloat) originy height: (cgfloat) frameheight{    =  Cgpathcreatemutable ();    Cgpathaddrect (Path, NULL, CGRectMake (0// ) The position value of path at this time is the value         in the Coretext coordinate system = ctframesettercreateframe (framesetter, Stringrange, Path, NULL);        Cfrelease (frame);    Cfrelease (path);         return frame;}

The point to note here is where the code is annotated, and the coordinates used in the typesetting process are in the Coretext coordinate system, that is, the origin is in the lower-left corner of the screen.

4. Render ctframe to the context of the view

This step is to draw the ctframe from the DrawRect method in the View class:

-(void) DrawRect: (cgrect) rect{    [Super Drawrect:rect];         // To convert a coordinate system to a coordinate system    under Coretext Cgcontextref context = uigraphicsgetcurrentcontext ();    Cgcontextsettextmatrix (context, cgaffinetransformidentity);     0 , self.bounds.size.height);     1.0,-1.0);         if (Ctframe! = Nil)     {        Ctframedraw (ctframe, context);}      }

The key to this step is the conversion of the coordinate system, because the drawing area contained in the Ctframe is in the Coretext coordinate system, so you should first convert the coordinate system to the Coretext coordinate system before drawing to ensure that the drawing position is correct.

This is described later if you need to make the exact line or font available ctline and ctrun when rendering.

iOS Reader Practice Series (i) Coretext Plain text typesetting basics

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.