iOS coretext Framework Chapter 1 Basic Knowledge

Keywords: Attribute Mac iOS

API interface documentation.

https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_Framework_Ref/_index.html


Several of the most commonly used classes in the CoreText framework:

  1. CTFont
  2. CTFontCollection
  3. CTFontDescriptor
  4. CTFrame
  5. CTFramesetter
  6. CTGlyphInfo
  7. CTLine
  8. CTParagraphStyle
  9. CTRun
  10. CTTextTab
  11. CTTypesetter

First, let's look at the overall window portfolio of the framework.


The CTFrame as a whole canvas consists of rows (CTLines), each of which can be divided into one or more small squares (CTRun s).

Note: You don't need to create CTRun yourself. Core Text will automatically create CTRun based on the attributes of NSAttributedString. Each CTRun object corresponds to different attributes, so you can freely control font, color, word spacing and so on.

Usually deal with steps:

1. Using core text is to first have a string to display, then define the style of each part of the string - > attributed String - > generate CTFramesetter - > get CTFrame - > draw (CTFrameDraw)
Among them, line-breaking, alignment, size of drawing area can be set in more detail.
2. Drawing just shows, clicking events need a judgment.
The CTFrame contains multiple CTLines, and the actual location and size of each line can be obtained. Judge whether the click is on a line or not. ctline can also determine the text range at this point (relative to the coordinates of ctline). Then traverse all the NSText Checking Result of the string, and judge whether the click is on the rang according to the result, so as to get the link and location of the click.


II. COORDINATE SYSTEM

In iOS UIKit, UIView is originated from the upper left corner, while Core Text is initially positioned using a typesetting system with desktop applications. The coordinate system of desktop applications is originated from the lower left corner, that is, Core Text is also drawn with reference to the lower left corner as the origin, so the current coordinate system needs to be processed.

In fact, the context in Core Graphic is also based on the lower left corner, but why don't we need to deal with the coordinate system when we draw some simple graphics with Core Graphic, because the current context obtained by UIGraphics GetCurrentContext () has been processed by this method. You can see the current context of the specified context by the following method Graphic state transformation matrix.

Method 1

// Because Core Text is used in conjunction with Core Graphic, like Core Graphic, when drawing, you need to get the current context to draw CGCo.
NtextRef context = UIGraphics GetCurrent Context (); NSLog (@ Current Context Transform Matrix%@), NSStringFromCGAffine Transform (CGContextGetCTM (context); //Flip the current coordinate system (because for the underlying rendering engine, the bottom left corner of the screen is (0, 0)) CGContextSetTextMatrix (context, CGAffine Transform Identity);
// Set the font transformation matrix to CGAffineTransform Identity, that is to say, every font does not do graphical transformation CGAffineTransform flipVertical = CGAffineTransform Make (1,0,0, -1,0, self.bounds.size.height); CGContext ConcatCTM (context, pVertical); // flipNSLog(@ Transform Matrix%@ after flipping), NSString CGAffineTransform ORM (CGContext GetCTM (context));

The printing results are as follows:

The transformation matrix of the current context [2, 0, 0, -2, 0, 800] after flipping the context [2, 0, 0, 2, 0, 0]


Method two
// Because Core Text is used in conjunction with Core Graphic, like Core Graphic, when drawing, you need to get the current context to draw CGContextRef context = UIGraphics GetCurrentContext (); NSLog (@ Current Context Transform Matrix%@), NSString FromCGAffine Transform (CGContextGetCTM (context)); //Flip the current coordinate system (because for the underlying drawing engine) For example, the bottom left corner of the screen is (0, 0)) CGContextSetTextMatrix(context, CGAffine Transform Identity; CGContext Translate CTM (context, 0, self. bounds. size. height); CGContext Scale CTM (context, 1.0, - 1.0); NSLog (@ Transform Matrix of Flipped Context%@), NSString FromCGAffine Transform (context));

Print:
The current context transformation matrix [2, 0, 0, -2, 0, 800] flips and the context transformation matrix [2, 0, -0, 2, 0, 0]

It can be found that the values of transformation matrix and CGAffine Transform Identity [1, 0, 0, 1, 0, 0] are different, and are related to whether the device is a Retina screen and device size. His function is to flip the context space coordinate system and make the origin of the lower left corner become the origin of the upper left corner, and turn the upward positive Y axis into the downward positive y axis. So when drawing Rect is used, the current context has been reversed. If the current coordinate system is not processed, it will be found that the rendered text is mirror upside down. So you need to Flip the context before you draw the Core Text on the context of the drawRect method of UIView.


3. Basic knowledge of fonts:

Font: A series of characters with the same size, style and pound value (e.g. 10 pounds of bold Palatino). Nowadays, most of them are regarded as synonyms of words.

Face: A combination of the pounds and formats of all fonts

Font family: is a set of related fonts (e.g. Franklin family includes Franklin Gothic, Fran-klin Heavy and Franklin Compressed)

Weight: Used to describe the size of a font. Typical pound values, from the thickest to the finest, are extremely fine, fine, book, medium, semi-thick, coarse, relatively coarse and extremely coarse.

Style: There are three forms of glyph: Roman type is straight; oblique type is italic; utakuc type is italic and curved (more like calligraphy than Roman type).

X height: The average height of lowercase letters (based on x). Two letters with the same pound value, the larger the x-height, the larger the letter looks than the smaller the x-height.

Cap height: Similar to x height. Average height of capital letters (based on C)

Descender: In the letter q, for example, the letter part below the baseline is called the downward extension part.

Ascender: The part above the height of X (e.g. the letter b) is called the uppermost part.

Baseline: The line usually under x, v, b, m

Stroke: Lines or curves that make up characters. Character shapes can be coarsened or changed

Serif: A horizontal line used to make characters more visible. For example, the upper left corner and the lower horizontal line of the letters.

Sans Serif: It allows typesetters not to use serif decoration.

Block: The strokes in this font make the characters look more conspicuous than those without serifs, but not to the extent of common serifs. For example, Lubalin Graph is a square character, which looks like a block of wood carved.

Calligraphic script: A font that imitates handwriting. For example, Murray Hill or Fraktur fonts

Decorative: Paintiful fonts

Pi symbol: A special symbol for non-standard alphanumeric characters. For example, Wingdings and Mathematical Pi

Ligature: A series of connected letters such as fi, fl, ffi or ffl. Because these letters are often linked because of their shape, typesetters have become accustomed to connecting them.





IV. MAIN FUNCTIONS

1. Enter the CTFrame and return an array containing multiple CTLine objects.

CFArrayRef CTFrameGetLines(        CTFrameRef frame ) CT_AVAILABLE(10_5, 3_2);

2. Get the number of elements in an array

CFIndex CFArrayGetCount(CFArrayRef theArray);

3. Get the idx element in the array

const void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx);

4. Get all the basic origins of CTLineRef, pass them into CTFrame, CFRange, and a CGPoint structure array pointer. This function will write the origin coordinates of each CTLine into the array.

void CTFrameGetLineOrigins(        CTFrameRef frame,        CFRange range,        CGPoint origins[] ) CT_AVAILABLE(10_5, 3_2);

5. Getting Range of CTLine Chinese Characters in the Whole Text

CFRange CTLineGetStringRange(    CTLineRef line ) CT_AVAILABLE(10_5, 3_2);

6. Get the CTRun array in CTLine

CFArrayRef CTLineGetGlyphRuns(    CTLineRef line ) CT_AVAILABLE(10_5, 3_2);

7. Get Range of CTRun in the whole text

CFRange CTRunGetStringRange(    CTRunRef run ) CT_AVAILABLE(10_5, 3_2);

8. Get the index of the position text in the whole text at the click

CFIndex CTLineGetStringIndexForPosition(    CTLineRef line,    CGPoint position ) CT_AVAILABLE(10_5, 3_2);

9. Get the x value of the character at the charIndex position relative to the origin of line in the whole text

CGFloat CTLineGetOffsetForStringIndex(    CTLineRef line,    CFIndex charIndex,    CGFloat * __nullable secondaryOffset ) CT_AVAILABLE(10_5, 3_2);

10. Get the number of glyphs in an array

CFIndex CTLineGetGlyphCount(    CTLineRef line ) CT_AVAILABLE(10_5, 3_2);

11. Set the coordinates of CoreText before drawing. Setting Baseline Position

CG_EXTERN void CGContextSetTextPosition(CGContextRef __nullable c,    CGFloat x, CGFloat y)    CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

12. Draw CTLine.

void CTLineDraw(    CTLineRef line,    CGContextRef context ) CT_AVAILABLE(10_5, 3_2);

13. Get the upper and lower heights and spacing of CTLine

double CTLineGetTypographicBounds(    CTLineRef line,    CGFloat * __nullable ascent,    CGFloat * __nullable descent,    CGFloat * __nullable leading ) CT_AVAILABLE(10_5, 3_2);

14. Setting up the current text matrix

CG_EXTERN void CGContextSetTextMatrix(CGContextRef __nullable c,    CGAffineTransform t)    CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

15. To get the range of a line of text is to take the pixel matrix of the line of text points as an image image to get the whole rectangular area. The offset and width relative to the origin of each line of baseline (e.g. {1.2, -2.57227}, {208.025, 19.2523}) are 1.2 units to the right, 2.57227 units to the downward and 2.57227 units to the rear relative to the origin of the baseline itself.

CGRect CTLineGetImageBounds(    CTLineRef line,    CGContextRef __nullable context ) CT_AVAILABLE(10_5, 3_2);

For example:

// Get the CTLineRef array CFArrayRef Lines in the frame = CTFrameGetLines (frame); //Get the number of CFIndex lineCount = CFArrayGetCount(Lines); //Get the first CTLineRefCTLineRef lineRef in the array = CFArrayGetValueAtIndex (Lines, 0); //line Get the CTRunRef array CFArruyRefs = CTLineGetGlyphRuns (lineRef); //Get the number of CF Ref lines in the array; Dex rus = CTLineGetGlyphCount(lineRef); // Get the number of CFIndex runCount = CFArray GetCount (runs); NSLog (@ "lines =% LD runs =% LD Rus = ld), lineCount, runCount, rus) in the array runs;

Print:

lines = 7   runs = 5 rus = 37

Character attribute name:

const CFStringRef kCTCharacterShapeAttributeName;              
// Font shape attribute must be CFNumberRef object default 0, non-zero corresponding to the corresponding character shape definition, such as 1 for traditional character shape
const CFStringRef kCTFontAttributeName;                        

//Font properties must be CTFont objects
const CFStringRef kCTKernAttributeName;                        
//The character interval property must be a CFNumberRef object
const CFStringRef kCTLigatureAttributeName;                 
//Set whether to use the hyphen property and set it to 0, which means not to use the hyphen property. Standard English hyphens are FI,FL.The default value is 1, which uses standard conjunctions. That's when the search finds it. f When you do, you will fl As a word.Must be CFNumberRef The default is 1.,Desirable 0,1,2
const CFStringRef kCTForegroundColorAttributeName;             
//The font color attribute must be a CGColor object, defaulting to black
const CFStringRef kCTForegroundColorFromContextAttributeName; 
 //The font color attribute of the context must be CFBooleanRef by default to False.
const CFStringRef kCTParagraphStyleAttributeName;              
//Paragraph style attributes must be CTParagraphStyle objects default to NIL
const CFStringRef kCTStrokeWidthAttributeName;              
//Stroke line width must be CFNumberRef object, silent 0.0f, standard 3.0f
const CFStringRef kCTStrokeColorAttributeName;              
//The color attribute of the stroke must be a CGColorRef object, defaulting to foreground color.
const CFStringRef kCTSuperscriptAttributeName;              
//Setting the superscript and subscript attributes of fonts must be CFNumberRef object default to 0, can be - 1 as the subscript, 1 as the superscript, need font support. Style Cn1 such as permutation and combination
const CFStringRef kCTUnderlineColorAttributeName;           
//The underline color attribute of a font must be a CGColorRef object, default to foreground color
const CFStringRef kCTUnderlineStyleAttributeName;           
//Font underline style attributes must be CFNumberRef objects, and kCTUnderlineStyleNone can modify the underline style through CTUnderlineStypleModifiers
const CFStringRef kCTVerticalFormsAttributeName;
//The font orientation property of text must be CFBooleanRef default to false, false to horizontal, true to vertical.
const CFStringRef kCTGlyphInfoAttributeName;
//Font information properties must be CTGlyphInfo objects
const CFStringRef kCTRunDelegateAttributeName
// The CTRun delegate attribute must be a CTRunDelegate object
Examples are given to illustrate:
    NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:@"This is a test of characterAttribute. Chinese characters"]; 





//Setting font properties  
  CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);  
  [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)]; 


    //Setting italics  
        CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 14, NULL);  
        [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];  




    //Underline  
        [mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];   



    //Set font segregation eg:test   
        long number = 10;  
        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);  
        [mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)];  


Even the word can not be used, did not see the effect.

There was no obvious effect.
  1. // Setting up hollow characters
  2.     long number = 2;  
  3.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);  
  4.     [mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])];  

  1. //Setting Hollow Characters  
  2.     long number = 2;  
  3.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);  
  4.     [mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])];  
  5.        
  6.     //Setting Hollow Character Color  
  7.     [mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])];  

When setting the color of hollow characters, we must first make the font hollow, otherwise setting the color is ineffective.

  1. //Setting multiple attributes for the same font paragraph  
  2.     //gules  
  3.     NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(id)[UIColor redColor].CGColor forKey:(id)kCTForegroundColorAttributeName];  
  4.     //Italics  
  5.     CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 40, NULL);  
  6.     [attributes setObject:(id)font forKey:(id)kCTFontAttributeName];  
  7.     //Underline  
  8.     [attributes setObject:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] forKey:(id)kCTUnderlineStyleAttributeName];  
  9.       
  10.     [mabstring addAttributes:attributes range:NSMakeRange(0, 4)];  

Finally, draw.

  1. -(void)characterAttribute  
  2. {  
  3.     NSString *str = @"This is a test of characterAttribute. Chinese characters";  
  4.     NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:str];  
  5.       
  6.     [mabstring beginEditing];  
  7.     /* 
  8.     long number = 1; 
  9.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); 
  10.     [mabstring addAttribute:(id)kCTCharacterShapeAttributeName value:(id)num range:NSMakeRange(0, 4)]; 
  11.     */  
  12.     /* 
  13.     //Setting font properties 
  14.     CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL); 
  15.     [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)]; 
  16.     */  
  17.     /* 
  18.     //Setting font segregation eg:test 
  19.     long number = 10; 
  20.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); 
  21.     [mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)]; 
  22.     */  
  23.   
  24.     /* 
  25.     long number = 1; 
  26.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); 
  27.     [mabstring addAttribute:(id)kCTLigatureAttributeName value:(id)num range:NSMakeRange(0, [str length])]; 
  28.      */  
  29.     /* 
  30.     //Setting font color 
  31.     [mabstring addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 9)]; 
  32.      */  
  33.     /* 
  34.     //Set font color to foreshadow color 
  35.     CFBooleanRef flag = kCFBooleanTrue; 
  36.     [mabstring addAttribute:(id)kCTForegroundColorFromContextAttributeName value:(id)flag range:NSMakeRange(5, 10)]; 
  37.      */  
  38.       
  39.     /* 
  40.     //Setting Hollow Characters 
  41.     long number = 2; 
  42.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); 
  43.     [mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])]; 
  44.       
  45.     //Setting Hollow Character Color 
  46.     [mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])]; 
  47.      */  
  48.       
  49.     /* 
  50.     long number = 1; 
  51.     CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number); 
  52.     [mabstring addAttribute:(id)kCTSuperscriptAttributeName value:(id)num range:NSMakeRange(3, 1)]; 
  53.     */  
  54.       
  55.     /* 
  56.     //Setting italics 
  57.     CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 14, NULL); 
  58.     [mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)]; 
  59.     */   
  60.       
  61.     /* 
  62.     //Underline 
  63.     [mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];  
  64.     //Underline colour 
  65.     [mabstring addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 4)]; 
  66.      */  
  67.       
  68.       
  69.       
  70.     //Setting multiple attributes for the same font paragraph  
  71.     //gules  
  72.     NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(id)[UIColor redColor].CGColor forKey:(id)kCTForegroundColorAttributeName];  
  73.     //Italics  
  74.     CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 40, NULL);  
  75.     [attributes setObject:(id)font forKey:(id)kCTFontAttributeName];  
  76.     //Underline  
  77.     [attributes setObject:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] forKey:(id)kCTUnderlineStyleAttributeName];  
  78.       
  79.     [mabstring addAttributes:attributes range:NSMakeRange(0, 4)];  
  80.        
  81.   
  82.       
  83.     NSRange kk = NSMakeRange(0, 4);  
  84.       
  85.     NSDictionary * dc = [mabstring attributesAtIndex:0 effectiveRange:&kk];  
  86.       
  87.     [mabstring endEditing];  
  88.       
  89.     NSLog(@"value = %@",dc);  
  90.       
  91.   
  92.       
  93.     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mabstring);  
  94.       
  95.     CGMutablePathRef Path = CGPathCreateMutable();  
  96.       
  97.     CGPathAddRect(Path, NULL ,CGRectMake(10 , 0 ,self.bounds.size.width-10 , self.bounds.size.height-10));  
  98.       
  99.     CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);      
  100.       
  101.     //Get the current (View) context for later drawings, this is an off-screen.  
  102.     CGContextRef context = UIGraphicsGetCurrentContext();  
  103.       
  104.     CGContextSetTextMatrix(context , CGAffineTransformIdentity);  
  105.       
  106.     //Stack, press into the graphics state stack. Each graphics context maintains a graphics state stack, not all elements of the graphics state of the current painting environment are saved. The current path is not considered in the graphics state, so it is not saved.  
  107.     //Save the current context graphics state. Whatever subsequent drawing on context will not affect the real screen.  
  108.     CGContextSaveGState(context);  
  109.       
  110.     //x, y axis moving  
  111.     CGContextTranslateCTM(context , 0 ,self.bounds.size.height);  
  112.       
  113.     //Scale x, y axis direction, -1.0 is 1.0 times the reverse, coordinate system conversion, flip 180 degrees along the X axis  
  114.     CGContextScaleCTM(context, 1.0 ,-1.0);  
  115.       
  116.     CTFrameDraw(frame,context);  
  117.       
  118.     CGPathRelease(Path);  
  119.     CFRelease(framesetter);  
  120. }  

  1. - (void)drawRect:(CGRect)rect  
  2. {  
  3.     [self characterAttribute];  
  4. }  


CORETEXT Framework


For more information on Context, please refer to http://www.padovo.com/blog/2013/01/31/study-coretext./





   


        
    

Posted by shanx24 on Wed, 27 Mar 2019 19:06:29 -0700