hello!大家都知道UILabel,UITextView这些个控件,只能显示简单的文本格式,如果想要图文混排等复杂的效果,就要用到CoreText框架来实现,不过有些个复杂。
首先是要了解一下coretext的概念:
The Core Text framework is an advanced, low-level technology for laying out text and handling fonts. Designed for high performance and ease of use, the Core Text layout engine is up to twice as fast as ATSUI (Apple Type Services for Unicode Imaging). The Core Text layout API is simple, consistent, and tightly integrated with Core Foundation, Core Graphics, and Cocoa.
核心文本框架是一种先进的,低层次的技术奠定了文本和字体处理。专为高性能和易用性,的核心文本布局引擎快两倍,为ATSUI (苹果类型服务为Unicode的影像) 。核心文本布局API很简单,一致和紧密集成的Core Foundation, Core Graphics和Cocoa。
Core Text is not meant to replace the Cocoa text system, although it provides the underlying implementation for many Cocoa text technologies. If you can deal with high-level constructs, such as text views, you can probably use Cocoa. For this reason, Cocoa developers typically have no need to use Core Text directly. Carbon developers, on the other hand, will find Core Text faster and easier to use, in many cases, than preexisting OS X text layout and font APIs.
核心文本并不是要取代Cocoa文本系统,虽然它提供了许多Cocoa文本技术的底层实现。如果你能处理高层次的结构,如viewtext,你也许可以使用cocoa。出于这个原因, Cocoa开发通常没有必要直接使用核心文本。 Carbon开发,另一方面,在许多情况下,比预先存在的OS X的文本布局和字体的API ,会发现核心内容更快,更容易使用。
找了一遍讲的比较详细的文章来讲cocotext核心文本,这个已经是比较详细的了:
来自:http://www.raywenderlich.com/4147/core-text-tutorial-for-ios-making-a-magazine-app
Core Text is a text engine found in iOS 3.2+ and OSX 10.5+ that gives you fine-grained control over text layout and formatting.
It sits in the sweet spot between UIKit and Core Graphics/Quartz:
- In UIKit you have UILabel and you add a word or a text line on the screen by simple Drag-and-Drop in IB, but you cannot change the color of individual words.
- In Core Graphics/Quartz you can do pretty much everything the system is capable of, but you need to calculate the position of each glyph in your text and draw it on the screen.
- Core Text lies right between the two! You have complete control over position, layout, attributes like color and size, but Core Text takes care of everything else for you – from word wrap to font rendering and more.
Core Text is especially handy if you are creating a magazine or book app – which work great on the iPad!
This Core Text tutorial for iOS will get you started by taking you through the process of creating a very simple Magazine application using Core Text – for Zombies!
You’ll learn how to:
- lay formatted text down on the screen;
- fine tune the text’s appearance;
- add images inside the text content;
- and finally create a magazine app, which loads text markup to easily control the formatting of the rendered text.
- eat brains! Ok just kidding, that’s only for the readers of this magazine.
To get the most out of this Core Text tutorial, you need to know the basics of iOS development first. If you are new to iOS development, you should check out some of theother tutorials on this site first.
Without further ado, let’s make some happy zombies by making them their very own iPad magazine!
Setting up a Core Text project
Start up Xcode, go to File\New\New Project, choose the iOS\Application\View-based Application, and click Next. Name the project CoreTextMagazine, choose iPad as Device family, click Next, choose a folder to save your project in, and click Create.
Next thing you have to do is add the Core Text framework to the project:
- Click on the project file in the Project navigator (the strip on the left hand side)
- Next select your only target for this project “CoreTextMagazine” in the Targets list
- Click on the “Build phases” tab
- Expand the “Link Binary With Libraries” strip and click on the “+” button
- Choose “CoreText.framework” from the list and click “Add”
That’s all the setup you need – now it’s time to start adding some code!
Adding a Core Text view
To get on track with Core Text as fast as possible you are going to create a custom UIView, which will use Core Text in its drawRect: method.
Go to File\New\New File, choose iOS\Cocoa Touch\Objective-C class, and click Next. Enter UIView for Subclass of, click Next, name the new class CTView, and click Save.
In CTView.h just above @interface add the following code to include the Core Text framework:
|
In the next step you’re going to set this new custom view as the main view in the application.
Select in the Project navigator the XIB file “CoreTextMagazineViewController.xib”, and bring up the Utilities strip in XCode (this appears whe you select the third tab in the View section of the top toolbar). From the Utilities strip, select the third icon on the top toolbar to select the Identity tab.
Now just click in the white space in the Interface editor to select the window’s view – you should see in the Utilities strip in the field Class the text “UIView” appearing. Write in that field “CTView” and hit Enter.
Now your application will show your custom Core Text view when started, but we’ll do that in a moment – let’s first add the code to draw some text so we have what to test.
Open CTView.m and delete all the predefined methods. Enter the following code to draw a “Hello world” inside your view:
|
Let’s discuss this bit by bit, using the comment markers above to designate each section:
- Here you need to create a path which bounds the area where you will be drawing text. Core Text on the Mac supports different shapes like rectangles and circles, but for the moment iOS supports only rectangular shape for drawing with Core Text. In this simple example, you’ll use the entire view bounds as the rectangle where you will be drawing by creating a CGPath reference from self.bounds.
- In Core Text you won’t be using NSString, but rather NSAttributedString, as shown here. NSAttributedString is a very powerful NSString derivate class, which allows you apply formatting attributes to text. For the moment we won’t be using formatting – this just creates a string holding plain text.
- CTFramesetter is the most important class to use when drawing with Core Text. It manages your font references and your text drawing frames. For the moment what you need to know is that CTFramesetterCreateWithAttributedString creates a CTFramesetter for you, retains it and initializes it with the supplied attributed string. In this section, after you have the framesetter you create a frame, you give the CTFramesetterCreateFrame a range of the string to render (we choose the entire string here) and the rectangle where the text will appear when drawn.
- Here CTFrameDraw draws the supplied frame in the given context.
- Finally, all the used objects are released.
Note that when working with Core Text classes you use a set of functions like CTFramesetterCreateWithAttributedString and CTFramesetterCreateFrame instead of directly using Objective-C objects.
You might think to yourself “Why would I ever want to use C again, I thought I was done with that since we have Objective-C?!”
Well, many of the low level libraries on iOS are written in plain C for speed and simplicity. Don’t worry though, you’ll find the Core Text functions pretty easy to work with.
Just one important thing to remember though: don’t forget to always use CFRelease on the references you get from functions which have “Create” in their name.
Believe it or not, that’s all you need to draw some simple text using Core Text! Hit Run and see the result.
Well that does not seem right, does it? Like many of the low level APIs, Core Text uses a Y-flipped coordinate system. To make it even worse, the content is also rendered flipped downwards! Because of this, keep in mind that if you mix UIKit drawing and Core Text drawing, you might get weird results.
Let’s fix the content orientation! Add the following code just after this line “CGContextRef context = UIGraphicsGetCurrentContext();”:
|
This is very simple code, which just flips the content by applying a transformation to the view’s context. Just copy/paste it each time you do drawing with CT.
Now hit Run again – congrats on your first Core Text app!
The Core Text Object Model
If you are a bit confused about the CTFramesetter and the CTFrame – that’s OK. Here I’ll make a short detour to explain how Core Text renders text content.
Here’s what the Core Text object model looks like:
You create a CTFramesetter reference and you provide it with NSAttributedString. At this point, an instance of CTTypesetter is automatically created for you, a class that manages your fonts. Next you use the CTFramesetter to create one or more frames in which you will be rendering text.
When you create a frame you tell it the subrange of text that will be rendered inside its rectangle. Core Text then automatically creates a CTLine for each line of text and (pay attention here) a CTRun for each piece of text with the same formatting.
As an example, Core Text would create a CTRun if you had several words in a row colored red, then another CTRun for the following plain text, then another CTRun for a bold sentence, etc. Again: very important – you don’t create CTRun instances, Core Text creates them for you based on the attributes of the supplied NSAttributedString.
Each of these CTRun objects can adopt different attributes, so you have fine control over kerning, ligatures, width, height and more.
Onto the Magazine App!
To create this magazine app, we need the capability to mark some of the text as having different attributes. We could do this by directly using methods on NSAttributedString such as setAttributes:range, but this is unwieldy to deal with in practice (unless you like to painstakingly write a ton of code!)
So to make thing simpler to work with, we’ll create a simple text markup parser which will allow us to use simple tags to set formatting in the magazine content.
Go to File\New\New File, choose iOS\Cocoa Touch\Objective-C class, and click Next. Enter NSObject for Subclass of, click Next, name the new class MarkupParser.m, and click Save.
Inside MarkupParser.h delete all the text and paste this code – it defines few properties and the method to do the parsing:
|
Next open MarkupParser.m and replace the contents with the following:
|
As you see you start pretty easy with the parser code – it just contains properties to hold the font, text color, stroke width and stroke color. Later on we’ll be adding images inside the text, so you need an array where you’re going to keep the list of images in the text.
Writing a parser is usually pretty hard work, so I’m going to show you how to build a very very simple one using regular expressions. This tutorial’s parser will be very simple and will support only opening tags – i.e. a tag will set the style of the text after the tag, the style will be applied until a new tag is found. The text markup will look like this:
These are red and blue words.
and will produce output like this:
These are red and blue words.
For the purpose of this Core Text tutorial such markup will be quite sufficient. For your projects you can develop it further if you'd like to.
Let's get parsin'!
Inside the attrStringFromMarkup: method add the following:
|
There are two sections to cover here:
- First, you set the empty result string to which you'll be adding text as it's found.
- Next, you create a regex to match chunks of text and tags. This regex will basically match a string of text and a following tag. The regular expression basically says "Look for any number of characters, until you come across an opening bracket. Then match any number of characters until you hit a closing bracket. Or - stop processing when you hit the end of the string."
Why are we creating this regular expression? We're going to use it to search the string for every place it matches, and then 1) render the text chunk found; then 2) change the current styles according to what's found in the tag. This will be repeated until the text is over.
Very simple parser indeed, eh?
Now that you have the chunks of text and all the formatting tags (like the font tag you see a bit above) in the "chunks" array, you'll need to loop trough them and build the attributed string from the text and tags.
Add this to the method body:
|
Phew, this is a lot of code! But don't worry, we'll go over it here section by section.
- You iterate over the chunks matched by the prior regular expression, and in this section you split the chunks by the "<" character (the tag opener). As a result, in parts[0] you have the text to add to the result and in parts[1] you have the content of the tag that changes the formatting for the text that follows.
- Next you create a dictionary holding a number of formatting options - this is the way you can pass formatting attributes to a NSAttributedString. Have a look at the key names - they are Apple defined constants which are pretty self-explanatory (of you can check out Apple's Core Text String Attributes Reference for full details). By calling appendAttributedString: the new text chunk with applied formatting is added to the result string.
- Finally, you check if there's a tag found after the text; if it starts with "font" a regex is ran for every possible tag attribute. For the "face" attribute the name of the font is saved in self.font, for "color" I and you did a little trickery: for the text value "red" is taken by the colorRegex and then a selector "redColor" is created and performed on the UIColor
class - this (hehe) returns a UIColor instance of a red color. Note this trick works only for the predefined colors of UIColor (and can even cause your code to crash if you pass in a selector that does not exist!) but this is sufficient for this tutorial. The stroke color attribute works much like the color attribute, but if the value of strokecolor is "none" just sets the stroke widht to 0.0, so no stroke will be applied to the text.
Note: If you're unsatiably curious how the regular expressions in this section work, they are basically saying ("Use the look-behind assertion to look for any text that is preceded by color=". Then match any normal word character (which does not include a quote), which basically keeps matching until the close quote is found. For more details, check out Apple'sNSRegularExpression class reference.
Right! Half the work of rendering formatted text is done - now attrStringFromMarkup: can take markup in and spit a NSAttributedString out ready to be fed to Core Text.
So let's pass in a string to render, and try it out!
Open CTView.m and add this just before @implementation:
|
Find the line where attString is defined - replace it with the following code:
|
Above you make a new parser, feed it a piece of markup and it gives you back formatted text.
That's it - hit Run and try it for yourself!
Ain't that just awesome? Thanks to 50 lines of parsing we don't have to deal with text ranges and code heavy text formatting, we can just use now a simple text file to hold the contents of our magazine app. Also the simple parser you just wrote can be extended infinitely to support everything you'd need in your magazine app.
A Basic Magazine Layout
So far we have text showing up, which is a good first step. But for a magazine we'd like to have columns - and this is where Core Text becomes particularly handy.
Before proceeding with the layout code, let's first load a longer string into the app so we have something long enough to wrap across multiple lines.
Go to File\New\New File, choose iOS\Other\Empty, and click Next. Name the new file test.txt, and click Save.
Then add the text from this file into test.txt and save.
Open CTView.m and find the 2 lines where you create MarkupParser and NSAttributedString and delete them. We're taking the loading of the text file out of the drawRect: method, because that sort of code doesn't really belong there. It's the job of a UIView to display content given to it - not load content. We'll move the attString variable to an instance variable and property in this class later.
Next open CoreTextMagazineViewController.m, delete all the existing content, and add the following instead:
|
When the view of the application is loaded, the app reads the text from test.txt, converts it to an attributed string and then sets the attString property on the window's view. We haven't added that property to CTView yet though, so let's add that next!
In CTView.h define these 3 instance variables:
|
Then add the corresponding code in CTView.h and CTView.m to define a property for attString:
|
Now you can hit Run again to see the view showing the contents of the text file. Cool!
How to make columns out of this text? Luckily Core Text provides a handy function - CTFrameGetVisibleStringRange. This function tells you how much text will fit into a given frame. So the idea is - create column, check how much text fits inside, if there's more - create another column, etc. etc. (columns here will be CTFrame instances, since columns are just taller rectangles)
First of all - we are going to have columns, then pages, then a whole magazine, so... let's make our CTView subclass UIScrollView to get free paging and scrolling!
Open up CTView.h and change the @interface line to:
|
OK! We've got free scrolling and paging now available. We're going to enable the paging in a minute.
Up to now we were creating our framesetter and frame inside the drawRect: method. When you have columns and different formatting it's better to do all those calculations only once. So what we are going to do is have a new class "CTColumnView" which will only render CT content passed to it, and in our CTView class we're going to only once create instances of CTColumnView and add them as subviews.
So to summarize: CTView is going to take care of scrolling, paging and building the columns; CTColumnView will actually render the content on the screen.
Go to File\New\New File, choose iOS\Cocoa Touch\Objective-C class, and click Next. Enter UIView for "Subclass of", click Next, name the new class CTColumnView.m, and click Save. Here's the initial code for the CTColumnView class:
|
This class does pretty much what we've been doing up to now - it just renders a CTFrame. We're going to create an instance of it for each text column in the magazine.
Let's first add a property to hold our CTView's text frames and declare the buildFrames method, which will do the columns setup:
|
Now buildFrames can create the text frames once and store them in the "frames" array. Let's add the code to do so.
|
Let's look at the code.
- here we do some setup - define the x & y offsets, enable paging and create an empty frames array
- buildFrames continues by creating a path and a frame for the view's bounds (offset slightly so we have a margin).
- This section declares textPos, which will hold the current position in the text. It also declares columnIndex, which will count how many columns are already created.
- The while loop here runs until we've reached the end of the text. Inside the loop we create a column bounds: colRect is a CGRect which depending on columnIndex holds the origin and size of the current column. Note that we are building columns continuously to the right (not across and then down).
- This makes use of CTFrameGetVisibleStringRange function to figure out what portion of the string can fit in the frame (a text column in this case). textPos is incremented by the length of this range, and so the building of the next column can begin on the next loop (if there's more text remaining).
- Here, instead of drawing the frame like before, we pass it to the newly created CTColumnView, we store it in the self.frames array for later usage and we add it as subview to the scrollview
- Finally, totalPages holds the total number of pages generated, and the contentSize property of the CTView is set so when there's more than one page of content we get scrolling for free!
Now let's also call buildFrames when all the CT setup is done. Inside CoreTextMagazineViewController.m add at the end of viewDidLoad :
|
One more thing to do before giving the new code a try: in the file CTView.m find the method drawRect: and remove it. We do now all the rendering in the CTColumnView class, so we'll leave the CTView drawRect: method to be the standard UIScrollView implementation.
Alright... hit Run and you'll see text floating in columns! Drag right and left to go between pages ... awesome!
We have columns, formatted text, but we miss images. Turns out drawing images with Core Text is not that easy - it's a text framework after all.
But thanks to the fact we already have a little markup parser we're going to get images inside the text pretty quick!
Drawing Images in Core Text
Basically Core Text does not have possibility to draw images. However, since it's a layout engine, what it can do is leave an empty space where you want to draw a picture. And since your code is already inside a drawRect: method, drawing an image yourself is easy.
Let's look at how leaving an empty space in the text works. Remember all the text chunks are CTRun instances? You simply set a delegate for a given CTRun and the delegate object is responsible to let know Core Text what is the CTRun ascent space, descent space and width. Like so:
When Core Text "reaches" a CTRun which has a CTRunDelegate it asks the delegate - how much width should I leave for this chunk of data, how high should it be? This way you build a hole in the text - then you draw your image in that very spot.
Let's start by adding support for an "img" tag in our little markup parser! Open up MarkupParser.m and find "} //end of font parsing"; add the following code immediately after this line to add support for "img" tag:
|
Let's get a look at all that new code - actually parsing the "img" tag does pretty much the same as what you did already for the font tag. By using 3 regexes you effectively read the width, height and src attributes of the img tag. When done - you add a new NSDictionary to self.images holding the information you just parsed out plus the location of the image in the text.
Now look at section 1 - CTRunDelegateCallbacks is a C struct which holds references to functions. This struct provides the information you want to pass to the CTRunDelegate. As you can guess already getWidth is called to provide a width for the CTRun, getAscent provides the height of the CTRun, etc. In the code above you provide function names for those handlers; in a minute we're gonna add the function bodies too.
Section 2 is very important - imgAttr dictionary holds the dimentions of the image; this object is also retained as it is going to be passed to the function handlers - so, when getAscent handler triggers it'll get as a parameter imgAttr and will just read out the height of the image and provide the value to CT. Neat! (we'll get to this in a moment)
CTRunDelegateCreate in section 3 creates a delegate instance reference and binds the callbacks and the data parameter together.
In the next step you need to create the attributes dictionary (the same way as for the font formatting above), but instead of formatting attributes you pass the delegate instance. In the end you add a single space which will trigger the delegate and create the hole in the text where the image will be rendered later on.
Next step, which you already anticipated, is to provide the callback functions for the delegate:
|
ascentCallback, descentCallback and widthCallback only read the respective properties from the passed NSDictionary and provide them to CT. What deallocCallback does is that it releases the dictionary holding the image information - it's called when the CTRunDelegate gets deallocated, so you have chance to do your memory management there.
Now that your parser is handling "img" tags, let's adjust also the CTView to render them. We need a method to send the images array to the view, let's combine setting the attributed string and the images into one method. Add the code:
|
Now that CTView is prepared to accept an array with images, let's pass those from the parser to the view and render them!
Go to CoreTextMagazineViewController.m and find the line "[(CTView*)self.view setAttString: attString];" - replace it with the following:
|
If you lookup attrStringFromMarkup: in the MarkupParser class you'll see it saves all the image tags data into self.images. This is what you are passing now directly to the CTView.
To render images we'll have to know the exact frame of the run where the image should appear. To find the origin of that spot we need to take in account several values:
- contentOffset when the content is scrolled
- the offset of CTView's frame (frameXOffset,frameYOffset)
- the CTLine origin coordinates (CTLine might have offset in the beginning of paragraphs for example)
- finally the distance between CTRun's origin and the origin of the CTLine
Let's render those images! First of all we need to update the CTColumnView class:
|
So with this code update we add an ivar and a property called images where we will keep a list of the images appearing in each text column. To avoid declaring yet another new class to hold the image data insideimages we're going to store NSArray objects which will hold:
- a UIImage instance
- the image bounds - i.e. origin inside the text and size of the image
And now the code that calculates the images' position and attaches them to the respective text columns:
|
Note: Ultimate credit goes to David Beck for his example on looping over runs, on which this code builds upon.
I know at first this code looks really hard-core, but bear with me - we're at the end of the tutorial; this is the final push for glory!
Let's go section by section:
- CTFrameGetLines gives you back an array of CTLine objects.
- You get the origins of all the current frame's lines - in short: you get a list of the top-left coordinates of all the text lines.
- You load nextImage with the attribute data of the first image in the text and imgLocation holds the string position of that same image.
- CTFrameGetVisibleStringRange gives you the visible text range for the frame you're rendering - i.e. you get which part of the text you render at present, then you loop trough the images array until you find the first image, which is in the frame you render at present. In other words - you fast-forward to the images relevant to the piece of text you are rendering at the moment.
- You loop trough the text's lines and loads each line into the "line" variable.
- You loop trough all the runs of that line (you get them by calling CTLineGetGlyphRuns).
- You check whether the next image is located inside the range of the present run - if so then you have to go on and proceed to rendering the image at this precise spot.
- You figure out the width and height of the run, by using the CTRunGetTypographicBounds method.
- You figure out the origin of the run, by using the CTLineGetOffsetForStringIndex and other offsets.
- You load the image with the given name in the variable "img" and get the rectangle of the current column and eventually the rectangle where the image needs to be rendered.
- You create an NSArray with the UIImage and the calculated frame for it, then you add it to the CTColumnView's image list
- In the end the next image in the list is loaded if one exists and the loop goes on over the text's lines.
OK! Great! Almost there - one tiny final step: find in CTView.m the line "[content setCTFrame:(id)frame];" and add below it:
|
Now you have all the code working, but you don't have great content to visualize...
No fear, I've prepared the next issue of Zombie Monthly - a montly popular magazine for zombies - for you; just do the following to import the content:
- In the project navigator delete test.txt that you created earlier
- Download and unarchive this file Zombie mag materials.
- Drag all the files over your Xcode project to import them. Make sure that "Copy items into destination group's folder (if needed)" is selected, and click Finish.
Then switch to CoreTextMagazineViewController.m and switch the line that gets the path to the file to use the new zombies.txt instead:
|
That's it - compile and run, and enjoy the latest issue of Zombie Monthly! :)
Just one final touch. Say we want to make the text in the columns justified so they fill the entire width of the column. Add the following code to make this happen:
|
This should get you started with paragraph styling; lookup kCTParagraphStyleSpecifierAlignment in Apple's Core Text documentation to get to the list of all paragraph styles you can control.
When to use Core Text and why?
Now that your Magazine App with Core Text is finished you might be asking yourself: "Why would I use Core Text over UIWebView?"
Well both CT and UIWebView are useful in their own context.
Don't forget UIWebView is a full-blown web browser and using it to visualize a single multicolored line of text is a huge overkill.
Imagine you have 10 multicolor labels in your UI- this means you're going to consume the memory for 10 Safaris (ok, almost, but you get the point).
So, keep in mind: UIWebView is a great web browser for when you need one, while Core Text is an efficient text rendering engine.
Where To Go From Here?
Here's the complete Core Text example project we developed in the above Core Text tutorial.
If you want to keep playing around with this project to learn more about Core Text, read up in Apple'sCore Text Reference Collection and see if you can add some of the following features to the app:
- Add more tags to the magazine engine parser
- Add support for more run styles
- Add more paragraph styles
- Add the ability to automatically apply styles to word bounds, paragraphs, sentences
- Enable ligatures and kerning - it's actually cool to enable ligatures and have a look at "if" and "fi" ;)
Since I know you are already thinking how to expand the parser engine beyond what I included in this short tutorial I have two recommendations for you:
- the fast lane to HTML parsing- use and extend Ben Reeves' Obj-C HTML Parser;
- or create your own grammar parser to do any wonder you come up with by using theObj-C ParseKit
If you have any questions, comments, or suggestions, please join in the forum discussion below!