Core Text Programming Guide

Core Text Programming Guide

ID:40057770

大小:325.59 KB

页数:30页

时间:2019-07-18

上传者:新起点
Core Text Programming Guide_第1页
Core Text Programming Guide_第2页
Core Text Programming Guide_第3页
Core Text Programming Guide_第4页
Core Text Programming Guide_第5页
资源描述:

《Core Text Programming Guide》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库

CoreTextProgrammingGuide ContentsIntroduction4OrganizationofThisDocument4SeeAlso4CoreTextOverview6OSXTextTechnologies6DesignGoalsandPrinciples7CoreTextFeaturesandCapabilities8SystemDataTypesandServices8CoreTextInput8CharactersandGlyphs9CoreTextObjects10LayoutObjects10FontObjects13CommonOperations15SimpleParagraphs15SimpleTextLabels16ColumnarLayout17ManualLineBreaking20FontCreationandStorage21AccessingFontMetrics25CreatingRelatedFonts27DocumentRevisionHistory292010-03-03|Copyright©2010AppleInc.AllRightsReserved.2 FiguresandListingsCoreTextOverview6Figure1-1GlyphsofthecharacterA9Figure1-2Ligatures9Figure1-3Textlayoutdataflow10Figure1-4Aframeobjectcontaininglinesandglyphruns12Figure1-5Creatingafontfromafontdescriptor14CommonOperations15Listing2-1Typesettingasimpleparagraph15Listing2-2Typesettingasimpletextlabel17Listing2-3Performingcolumnartextlayout18Listing2-4Performingmanuallinebreaking20Listing2-5Creatingafontdescriptorfromanameandpointsize21Listing2-6Creatingafontdescriptorfromafamilyandtraits21Listing2-7Creatingafontfromafontdescriptor23Listing2-8Serializingafont23Listing2-9Creatingafontfromserializeddata24Listing2-10Calculatinglineheight26Listing2-11Gettingglyphsforcharacters26Listing2-12Changingtraitsofafont27Listing2-13Convertingafonttoanotherfamily282010-03-03|Copyright©2010AppleInc.AllRightsReserved.3 IntroductionCoreTextisanadvanced,low-leveltechnologyforlayingouttextandhandlingfonts.Itisdesignedforhighperformanceandeaseofuse.TheCoreTextAPI,introducedinOSXv10.5,isaccessiblefromallOSXapplicationenvironments.ItisalsoavailableiniOS3.2.TheCoreTextlayoutengineisdesignedspecificallytomakesimpletextlayoutoperationseasytodoandtoavoidsideeffects.TheCoreTextfontprogramminginterfaceiscomplementarytotheCoreTextlayoutengineandisdesignedtohandleUnicodefontsnatively,unifyingdisparateOSXfontfacilitiesintoasinglecomprehensiveprogramminginterface.Thisdocumentisintendedfordeveloperswhoneedtodotextlayoutandfonthandlingatalowlevel.Ifyoucandevelopyourapplicationusinghigher-levelconstructs,suchasNSTextView,thenyoushouldusetheCocoatextsystem,introducedinTextSystemOverview.If,ontheotherhand,youneedtorendertextdirectlyintoaCoreGraphicscontext,thenyoushoulduseCoreText.MoreinformationaboutthepositionofCoreTextamongotherOSXtexttechnologiesispresentedin“OSXTextTechnologies”(page6).Important:ThisdocumenthasnotbeenupdatedtoaddresstheuseofCoreTextiniOS3.2.OrganizationofThisDocumentThisdocumentisorganizedintothefollowingchapters:“CoreTextOverview”(page6)describestheCoreTextsystemintermsofitsdesigngoalsandfeatureset.Italsointroducestheopaquetypesthatencapsulatethetextlayoutandfonthandlingcapabilitiesofthesystem.“CommonOperations”(page15)presentssnippetsofcodewithcommentaryillustratingtypicalusesofthemainCoreTextopaquetypes.SeeAlsoInadditiontothisdocument,thereareseveralthatcovermorespecificaspectsofCoreTextordescribethesoftwareservicesusedbyCoreText.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.4 IntroductionSeeAlso●CoreTextReferenceCollectionprovidescompletereferenceinformationfortheCoreTextlayoutandfontAPI.●CoreTextTestisasamplecodeprojectthatshowshowtouseCoreTextinthecontextofacompleteCarbonapplication.●CoreTextArcCocoaisasamplecodeprojectthatillustratestheuseoffonts,lines,andrunsinaCoreTextCocoaapplication.●CoreFoundationDesignConceptsandCoreFoundationFrameworkReferencedescribeCoreFoundation,aframeworkthatprovidesabstractionsforcommondatatypesandfundamentalsoftwareservicesusedbyCoreText.ThefollowingdocumentsprovideentrypointstothedocumentationdescribingtheCocoatextsystem.●TextSystemOverviewgivesanintroductiontotheCocoatextsystem.●TextLayoutProgrammingGuideforCocoadescribestheCocoatextlayoutengine.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.5 CoreTextOverviewTheCoreTextframeworkisanadvanced,low-leveltechnologyforlayingouttextandhandlingfonts.Designedforhighperformanceandeaseofuse,theCoreTextlayoutengineisuptotwiceasfastasATSUI(AppleTypeServicesforUnicodeImaging).TheCoreTextlayoutAPIissimple,consistent,andtightlyintegratedwithCoreFoundation,CoreGraphics,andCocoa.TheCoreTextfontAPIiscomplementarytotheCoreTextlayoutengine.CoreTextfonttechnologyisdesignedtohandleUnicodefontsnatively,bridgingthegapbetweenCarbonandCocoafontreferences,andprovidingefficientfonthandlingforCoreTextlayout.CoreTextbringsthecapabilitiesandcoherentdesignofCocoatextandfontstoabroader,lower-levelclientbase.OSXTextTechnologiesTheMacintoshoperatingsystemhasprovidedsophisticatedtexthandlingandtypesettingcapabilitiesfromitsbeginning.Infact,thesefeaturessparkedthedesktoppublishingrevolution.CoreTextisthemostmoderntext-handlingtechnologyontheplatform.ItisdesignedspecificallyforOSXandiswritteninC,soitcanbecalledfromanylanguageinthesystem.Itispositionedasacoretechnologytoprovideconsistent,high-performancetextservicestootherframeworksthroughoutthesystem,andtheCoreTextAPIisaccessibletoapplicationsthatneedtouseitdirectly.CoreTextresidesintheApplicationServicesumbrellaframework(ApplicationServices)sothatitiscallablefrombothCarbonandCocoaandhasallofthelower-levelservicesitneeds.CoreTextisnotmeanttoreplacetheCocoatextsystem,althoughitprovidestheunderlyingimplementationformanyCocoatexttechnologies.Ifyoucandealwithhigh-levelconstructs,suchastextviews,youcanprobablyuseCocoa.Forthisreason,CocoadeveloperstypicallyhavenoneedtouseCoreTextdirectly.Carbondevelopers,ontheotherhand,willfindCoreTextfasterandeasiertouse,inmanycases,thanpreexistingOSXtextlayoutandfontAPIs.TodecidewhetherCoreTextistherightOSXtexttechnologyforyourapplication,applythefollowingguidelines:●Ifyoucan,useCocoatext.TheNSTextViewclassisthemostadvanced,full-featured,flexibletextviewinOSX.Forsmallamountsoftext,useNSTextField.●Todisplaywebcontentinyourapplication,useWebKit.●IfyouneedtouseCarbononly,considerusingNSTextViewwithHICocoaView.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.6 CoreTextOverviewDesignGoalsandPrinciples●Ifyouneedalower-levelAPIfordrawinganykindoftextintoaQuartzgraphicscontext(CGContext),considerusingCoreTextdirectly.Generallyspeaking,CoreTextisforapplicationsthatneedalow-leveltext-handlingtechnologycorrelatingwiththeCoreGraphicsframework(Quartz).IfyouworkdirectlywithQuartzandyouneedtodrawsometext,useCoreText.If,forexample,youhaveyourownpagelayoutengine—youhavesometextandyouknowwhereitneedstogoinyourview—youcanuseCoreTexttogeneratetheglyphsandpositionthemrelativetoeachotherwithallthefeaturesoffinetypesetting,suchaskerning,ligatures,line-breaking,andjustification.DesignGoalsandPrinciplesCoreTextisdesignedtoprovidethefollowingbenefits:●Acomprehensive,unifiedsetoftext-layoutandfontAPIs●Highperformanceandeaseofuse●TightintegrationwithCocoa,CoreFoundation,andCoreGraphics(Quartz)●NativeUnicodehandling●64-bitapplicationsupport●Clean,simple,consistentAPIdesign●Simpleinterfacesforsimpleoperations●Aflexibleinterfacetolayoutandglyphdata●ApredictablecoststructureandrationaldivisionoflaborAprimarydesigngoalofCoreTextlayoutistomakesimplethingseasytodo.So,forexample,ifyouwanttodrawaparagraphoftextorasimpletextlabelonthescreen,youdon’tneedmuchcode.AcorollaryprincipleoftheCoreTextdesignisthatclientsarenotrequiredtopayforfeaturestheydon’tuse.TheobjectsdefinedbyCoreTextopaquetypesprovideaprogressionfromsimplicitytocomplexity,intermsoftheiruseandinterface.Thatis,higher-levelobjectsdomoreforyou,andsotheyareeasiertouse(althoughtheymaybemorecomplexinternally).Forexample,thehighest-levelobjectinCoreTextistheframesetter,whichfillsapath(definedbyaCGPathobjectrepresentingarectangle)withtext.TheframesetterobjectusesotherCoreTextobjects,suchastypesetter,line,andglyphrunobjects,toaccomplishitswork:creatingframeobjects,whicharelinesofglyphslaidoutwithinashape.Clientswhosimplyneedtolayoutaparagraphneedonlyworkwiththeframesetter.Clientswhoneedtointerveneinthetextlayoutprocessatalowerlevelcandealwithlowerlevelobjects,suchaslineobjects.Lineobjectscandrawthemselvesindividuallyorbeusedtoobtainglyphinformation.WithCoreTextyouusethehighest-levelobjectyoucantogetyourjobdone.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.7 CoreTextOverviewCoreTextFeaturesandCapabilitiesCoreTextFeaturesandCapabilitiesCoreTextperformstextlayoutandfontaccess.Thetextlayoutenginegeneratesglyphsfromcharactersandpositionstheglyphsintoglyphruns,lines,andmultilineframes.Italsoprovidesglyph-andlayout-relateddata,suchasglyphpositioningandmeasurementoflinesandframes.TheAPIhandlescharacterattributesandparagraphstyles,includingvarioustypesoftabstylesandpositioning.TheCoreTextfontAPIbringstoCarbondevelopersthesamecapabilitiesenjoyedbyCocoadevelopersthroughNSFontandNSFontDescriptor.TheAPIprovidesfontviewingandselecting.Itprovidesfontreferences,fontdescriptors(objectsthatencapsulatefontdatasufficienttoinstantiateafontreference),andeasyaccesstofontdata.Italsoprovidessupportformultiplemasterfonts,fontvariations,fontcascading,andfontlinking.TheCoreTextfontAPIisdesignedtobeverycomplete,sothatyoudon’thavetogotodifferentlayerstodowhatyouneedtodo.SystemDataTypesandServicesCoreTextusessystemdatatypesandserviceswhereverpossible,andyouusethesameconventionsthatpertaintotheothercoreframeworksinOSX.So,forexample,CoreTextusesCoreFoundationobjectsformanyinputandoutputparameters,enablingthemtoberetained,released,andstoredinCoreFoundationcollectionclasses.OtherobjectshandledbyCoreTextareprovidedbytheCoreGraphicsframework,forexample,CGPathobjects.Moreover,becausemanyCoreFoundationobjectsaretoll-freebridgedwithCocoaFoundationobjects,youcanusuallyuseFoundationobjectsinplaceofCoreFoundationobjectspassedintoCoreTextfunctions.Useofthesestandardtypesandtoll-freebridgingensurethatyoudon’thavetoperformexpensivetypeconversionstogetdataintoandoutofCoreText.CoreTextisbuilttoworkdirectlywithCoreGraphics,alsoknownasQuartz,whichisthehigh-speedgraphicsrenderingenginethathandlestwo-dimensionalimagingatthelowestlevelinOSX.Quartzistheonlywaytogetglyphsdrawnatafundamentallevel,and,becauseCoreTextprovidesalldatainaformdirectlyusablebyQuartz,theresultishigh-performancetextrendering.CoreTextInputTheinputtypemostbasictoCoreTextistheCoreFoundationattributedstring,representedbyCFAttributedStringReforitsCocoacounterpart,NSAttributedString,whicharetoll-freebridged.Theattributesarekey-valuepairsthatdefinestylecharacteristicsofthecharactersinthestring,whicharegroupedinrangesthatsharethesameattributes.Examplesoftextattributesarefontandcolor.Theattributesthemselvesarepassedintoattributedstrings,andretrievedfromthem,usingCFDictionaryobjects.(ThoughCFDictionaryRefandNSDictionaryarealsotoll-freebridged,theindividualattributeobjectsstoredinthedictionarymaynotbe.)ThetypesettingmechanisminCoreTextusestheinformationintheattributedstringtoperformcharacter-to-glyphconversion.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.8 CoreTextOverviewCoreTextFeaturesandCapabilitiesCharactersandGlyphsOneofthemostimportantcapabilitiesoffinetypesettingischaracter-to-glyphconversion.Itisimportanttodistinguishbetweencharactersandglyphsindiscussingatextlayoutengine.Charactersareessentiallynumbersrepresentingcodepointsinacharactersetorencodingscheme,suchasUnicode,thecharactersetusedforalltextinOSX.TheUnicodestandardprovidesauniquenumberforeverycharacterineverymodernwrittenlanguageintheworld,independentoftheplatform,program,andprogramminglanguagebeingused.Aglyphisagraphicshapeusedtodepictacharacter.Glyphsarealsorepresentedbynumericcodes,calledglyphcodes,thatareindexesintoaparticularfont.Glyphsareselectedduringcompositionandlayoutprocessingbythecharacter-to-glyphconversionprocess.Thereareanynumberofglyphsthatcorrespondtoaparticularcharacter.Forexample,thecharacter“uppercaseA”hasdifferentglyphsfordifferenttypefaces(suchasHelveticaandTimes)andtypestyles(suchasboldanditalic).Figure1-1showsvariousglyphs,allofwhichrepresentan“uppercaseA.“Figure1-1GlyphsofthecharacterAMoreover,thecorrespondencebetweencharactersandglyphsisnotonetoone,andthecontextwithinwhichacharacterappearscanaffecttheglyphchosentorepresentit.Forexample,inmanyfontsan“f”and“l”appearingside-by-sideinacharacterstringarereplacedbyaligature,whichisasingleglyphdepictingthelettersjoinedtogether.Figure1-2showstwoexamplesofindividualcharactersandthesingle-glyphligaturesoftenusedwhentheyareadjacent.Character-to-glyphconversionisacomplexanddifficulttaskthatCoreTextperformsquicklyandefficiently.Figure1-2Ligatures+=+=2010-03-03|Copyright©2010AppleInc.AllRightsReserved.9 CoreTextOverviewCoreTextObjectsCoreTextObjectsCoreTextobjectsarebasedonthecorrespondingopaquetypesdefinedbytheframework.Inthesectionsthatfollow,youlearnhowtheprimaryCoreTextobjectsinteracttoaccomplishvariousclienttasks.LayoutObjectsLayoutobjectsmakeuptheCoreTextlayoutengine.Thissectiondiscussestheprimarylayoutobjects:framesetter,frame,typesetter,line,andglyphrunobjects.InadditionthissectionbrieflydiscussestheotherCoreTextlayoutobjects:paragraphstyles,texttabs,andglyphinfoobjects.FramesettersandFramesTheframesetteristhehighest-levelobjectintheCoreTextlayoutengine,representedbytheCTFramesetteropaquetype.Aframesettergeneratestextframesbyfillingapathwithtext.Thatis,CTFramesetterisanobjectfactoryforCTFrameobjectsthatarereadytodraw.Theframesettertakesanattributedstringobject(CFAttributedString)andashapedescriptorobject(CGPath)andcallsintothetypesettertocreatelineobjectsthatfillthatshape.Theoutputisaframeobjectcontaininganarrayoflines.Thisarrayoflinesisaparagraph,amultilinelayout.Theframecandrawitselfdirectlyintoagraphiccontext.Youcanalsoretrievethelinestomanipulatebeforedrawing.Forexample,youmightadjusttheirpositioning.Figure1-3showsthedataflowamongobjectsperformingtextlayout.Figure1-3TextlayoutdataflowCFAttributedStringCTFramesetterCTFrameCTTypesetterCGPathTheframesetterappliesparagraphstylestotheframetextasitislaidout.ParagraphstylesarerepresentedinCoreTextbyobjectsstoringattributesthataffectparagraphlayout.Amongtheseattributesarealignment,tabstops,writingdirection,line-breakingmode,andindentationsettings.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.10 CoreTextOverviewCoreTextObjectsIt’sadvantageoustousetheframesettertoperformthecommonoperationoftypesettingamultilineparagraphbecauseithandlesallofthedetailsofproducingframes,instantiatingotherobjects,suchasthetypesetter,asneeded.TheCTFramesetteropaquetypeprovidesfunctionstocreateaframesetterwithanattributedstring,tocreateframeobjects,andtoreturnitstypesetter.AswithallCoreTextobjects,CTFramesettercanalsoreturnitsCoreFoundationtypeidentifier.TypesettersAtypesetterperformsthefundamentaltextlayoutoperationsofcharacter-to-glyphconversionandpositioningofthoseglyphsintolines.Thatis,itdetermineswhichglyphstouseandwheretoplacethemrelativetoeachother,producinglineobjects.TypesettersarerepresentedbytheCTTypesetteropaquetype.Thetypesetteralsosuggestslinebreaks.Itfindshowmanyglyphscanfitwithinasinglelinewithinagivenspace.Itthendeterminesthelengthofthelinebyusingwordbreaks,wordwrapping,orfiner-grainedclusterbreaks.Simplewordwrappingisthedefaultmethodofcreatinglinebreaks.Theframesetterinstantiatesatypesetterandusesittocreatethelineobjectsusedtofillaframe.Youcanalsouseatypesetterdirectly,asdescribedin“ManualLineBreaking”(page20).LinesandGlyphRunsAlineobjectrepresentsalineoftextandisrepresentedinCoreTextbytheCTLineopaquetype.ACTLineobjectcontainsanarrayofglyphruns.Lineobjectsarecreatedbythetypesetterduringaframesettingoperationand,likeframes,candrawthemselvesdirectlyintoagraphicscontext.Lineobjectsholdtheglyphsthataretheresultofthetextlayoutprocess,createdfromtextandstyleinformation.Alinecorrespondstoarangeofcharacters.Itcouldbemileslongor,moreoften,oneofaseriesoflinescontainedwithinaparagraph.TheparagraphisrepresentedinCoreTextbyaCTFrameobject,whichcontainstheparagraph’slineobjects.Accordingly,youcanretrievelineobjectsfromtheirframeobject.Alineobjectcontainsglyph-runobjects,representedbytheCTRunopaquetype.Aglyphrunisasetofconsecutiveglyphssharingthesameattributesanddirection.Thetypesettercreatesglyphrunsasitproduceslinesfromcharacterstrings,attributes,andfontobjects.Thatis,alineisconstructedofoneormoreglyphs2010-03-03|Copyright©2010AppleInc.AllRightsReserved.11 CoreTextOverviewCoreTextObjectsruns.Glyphrunscandrawthemselvesintoagraphiccontext,ifdesired,althoughmostclientshavenoneedtointeractdirectlywithglyphruns.Figure1-4showstheconceptualhierarchyofaframeobjectcontaininglineobjectsthat,inturn,containglyph-runobjects.Figure1-4AframeobjectcontaininglinesandglyphrunsaglyphrunandanotherrunCTRunCTLineCTFrameCTLinehasaconveniencemethodforcreatingafreestandinglineindependentofaframe,CTLineCreateWithAttributedString.Youcanusethismethodtocreatealineobjectdirectlyfromanattributedstringwithoutneedingtocreateandmanageatypesetter.Withoutatypesetter,however,there’snowaytocalculatelinebreaks,sothismethodismeantforasinglelineonly(forexample,creatingatextlabel).Afteryouhavealineobject,youcandoanumberofthingswithit.Forexample,youcanhavethelinecreateajustifiedortruncatedcopyofitself,andyoucanaskthelineforpenoffsetsforvariousdegreesofflushness.Youcanusethesepenoffsetstodrawthelinewithleft,right,orcenteredalignments.Youcanalsoaskthelineformeasurements,suchasitsimageboundsandtypographicbounds.Imageboundsrepresenttherectangletightlyenclosingthegraphicshapesoftheglyphsactuallyappearingintheline.Typographicboundsincludetheheightoftheascendersinthefontandthedepthofitsdescenders,regardlessofwhetherthosefeaturesappearintheglyphsinagivenline.Likeaframeobject,alineobjectisreadytodraw.YousimplysetthetextpositioninaCoreGraphicscontextandhavethelinedrawitself.CoreTextusesthesameplacementstrategyasQuartz,settingtheoriginofthetextonthetextbaseline.InQuartz,youspecifythelocationoftextinuser-spacecoordinates.Thetextmatrixspecifiesthetransformfromtextspacetouserspace.Thetextpositionisstoredinthetxandtyvariablesofthetextmatrix.Whenyoufirstcreateagraphicscontext,itinitializesthetextmatrixtotheidentitymatrix;thustext-spacecoordinatesareinitiallythesameasuser-spacecoordinates.Quartzconceptuallyconcatenatesthetextmatrixwiththecurrenttransformationmatrixandotherparametersfromthegraphicsstatetoproducethefinaltext-renderingmatrix,thatis,thematrixactuallyusedtodrawthetextonthepage.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.12 CoreTextOverviewCoreTextObjectsOtherLayoutObjectsInadditiontotheframesetter,frame,typesetter,andlineobjects,CoreTextprovidesotherobjectstocompletethetextlayoutprocess:paragraphstyle,texttab,andglyphinfoobjects.ParagraphstyleobjectsencapsulateparagraphorrulerattributesinanattributedstringandarerepresentedbytheCTParagraphStyleopaquetype.Aparagraphstyleobjectisacomplexattributevalueinanattributedstring,storinganumberofsubattributesthataffectparagraphlayoutforthecharactersofthestring.Amongthesesubattributesarealignment,tabstops,writingdirection,line-breakingmode,andindentationsettings.TheCTTextTabopaquetyperepresentsatabstopinaparagraphstyle,storinganalignmenttypeandlocation.TheCTGlyphInfoopaquetypeenablesyoutooverrideafont'sspecifiedmappingfromUnicodetotheglyphID.FontObjectsFontobjectsarethoseCoreTextobjectsdealingdirectlywithfonts:thefontreferenceitself,fontdescriptorobjects,andfontcollectionobjects.FontsFontsprovideassistanceinlayingoutglyphsrelativetooneanotherandareusedtoestablishthecurrentfontwhendrawinginagraphicscontext.TheCoreTextfontopaquetype(CTFont)isaspecificfontinstancethatencapsulatesalotofinformation.Itsreferencetype,CTFontRef,istoll-freebridgedwithNSFont.WhenyoucreateaCTFontobject,youtypicallyspecify(oruseadefault)pointsizeandtransformationmatrix,whichgivesthefontinstancespecificcharacteristics.Youcanthenquerythefontobjectformanykindsofinformationaboutthefontatthatparticularpointsize,suchascharacter-to-glyphmapping,encodings,fontmetricdata,andglyphdata,amongotherthings.Fontmetricsareparameterssuchasascent,descent,leading,capheight,x-height,andsoon.Glyphdataincludesparameterssuchasboundingrectanglesandglyphadvances.Therearemanywaystocreatefontreferences.ThepreferredmethodisfromafontdescriptorusingCTFontCreateWithFontDescriptor.YoucanalsouseanumberofconversionAPIs,dependingonwhatyouhavetostartwith.Forexample,youcanusethePostScriptnameofthetypeface(CTFontCreateWithName),anATSfontreference(CTFontCreateWithPlatformFont),aCoreGraphicsfontreference(CTFontCreateWithGraphicsFont),oraQuickDrawfontreference(CTFontCreateWithQuickdrawInstance).There’salsoCTFontCreateUIFontForLanguage,whichcreatesareferencefortheuser-interfacefontfortheapplicationyou’reusinginthelocalizationyou’reusing.CoreTextfontreferencesprovideasophisticated,automaticfont-substitutionmechanismcalledfontcascading.Thismechanismtakesfonttraitsintoaccount,soitdoesabetterjobthanpreviousschemesofpickinganappropriatefonttosubstituteforamissingfont.Fontcascadingisbasedoncascadelists,whicharearraysoforderedfontdescriptors.Thereisasystemdefaultcascadelist(whichispolymorphic,basedontheuser'slanguagesettingandcurrentfont)andafontcascadelistthatisspecifiedatfontcreationtime.Usingthe2010-03-03|Copyright©2010AppleInc.AllRightsReserved.13 CoreTextOverviewCoreTextObjectsinformationinthefontdescriptors,thecascadingmechanismcanmatchfontsaccordingtostyleaswellasmatchingcharacters.TheCTFontCreateForStringfunctionusescascadeliststopickanappropriatefonttoencodeagivenstring.YouspecifyandretrievefontcascadelistsusingthekCTFontCascadeListAttributeproperty.FontDescriptorsFontdescriptors,representedbytheCTFontDescriptoropaquetype,provideamechanismtodescribeafontcompletelywithadictionaryofattributes.CTFontDescriptorRefistoll-freebridgedtoNSFontDescriptor.TheattributesarepropertiessuchasPostScriptname,family,andstyle,andtraitssuchasbold,italic,andmonospace.ThefontdescriptorcanthenbeusedtocreateormodifyaCTFontobject.Fontdescriptorscanbeserializedandstoredinadocumenttoprovidepersistenceforfonts.Figure1-5illustratesthefontsystemusingafontdescriptortocreateaspecificfontinstance.Figure1-5CreatingafontfromafontdescriptorCTFontDescriptorCTFontFontSystemAfontdescriptorcanalsobeconsideredasaqueryintothefontsystem.Youcancreateafontdescriptorwithanincompletespecification,thatis,withoneorjustafewvaluesintheattributedictionary,andthesystemwillchoosethemostappropriatefontfromthoseavailable.ThesystemcanalsogiveyouacompletelistoffontdescriptorsmatchingyourqueryviaCTFontDescriptorCreateMatchingFontDescriptors.FontCollectionsFontcollectionsareunionsoffontdescriptors,thatis,groupsoffontdescriptorstakenasasingleobject.AfontcollectionisrepresentedbytheCTFontCollectionopaquetype.Fontcollectionsprovidethecapabilitiesoffontenumeration,accesstoglobalandcustomfontcollections,andaccesstothefontdescriptorscomprisingthecollection.Youcan,forexample,createafontcollectionofallthefontsavailableinthesystembycallingCTFontCollectionCreateFromAvailableFonts,andyoucanusethecollectiontoobtainanarrayofallofthememberfontdescriptors.Thereisalsoafunctionthattakesacallbackparameterusedtosortthereturnedarrayoffontdescriptors.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.14 CommonOperationsThischapterdescribessomecommontext-layoutandfont-handlingoperationsandshows,throughportionsofsamplecode,howtheycanbeaccomplishedusingCoreText.Inadditiontothecodefragmentsinthischapter,seethefollowingsamplecodeapplicationsthatuseCoreText:●CoreTextTestshowshowtouseCoreTexttotypesetblocksoftextwithvaryingattributesinthecontextofacompleteCarbonapplication.●CoreTextArcCocoaillustratestheuseofCoreTextfonts,lines,andrunsinaCocoaapplicationthatsetstypealonganarchedpath.SimpleParagraphsOneofthemostcommonoperationsintypesettingislayingoutamultilineparagraphwithinanarbitrarilysizedrectangulararea.CoreTextmakesthisoperationeasy,requiringonlyafewlinesofCoreText–specificcode.Tolayouttheparagraph,youneedagraphicscontexttodrawinto,arectangularpathtoprovidetheareawherethetextislaidout,andanattributedstring.Mostofthecodeinthisexampleisrequiredtocreateandinitializethecontext,path,andstring.Afterthatisdone,CoreTextrequiresonlythreelinesofcodetodothelayout.Listing2-1usesCocoatosimplifyinitializationofthegraphicscontext.ToseehowthatoperationisdoneinCarbon,seetheCoreTextTestsamplecodeor“GraphicsContexts“intheQuartz2DProgrammingGuide.Listing2-1Typesettingasimpleparagraph//Initializeagraphicscontextandsetthetextmatrixtoaknownvalue.CGContextRefcontext=(CGContextRef)[[NSGraphicsContextcurrentContext]graphicsPort];CGContextSetTextMatrix(context,CGAffineTransformIdentity);//Initializearectangularpath.CGMutablePathRefpath=CGPathCreateMutable();CGRectbounds=CGRectMake(10.0,10.0,200.0,200.0);CGPathAddRect(path,NULL,bounds);2010-03-03|Copyright©2010AppleInc.AllRightsReserved.15 CommonOperationsSimpleTextLabels//Initializeanattributedstring.CFStringRefstring=CFSTR("Weholdthistruthtobeself-evident,thateveryoneiscreatedequal.");CFMutableAttributedStringRefattrString=CFAttributedStringCreateMutable(kCFAllocatorDefault,0);CFAttributedStringReplaceString(attrString,CFRangeMake(0,0),string);//Createacolorandadditasanattributetothestring.CGColorSpaceRefrgbColorSpace=CGColorSpaceCreateDeviceRGB();CGFloatcomponents[]={1.0,0.0,0.0,0.8};CGColorRefred=CGColorCreate(rgbColorSpace,components);CGColorSpaceRelease(rgbColorSpace);CFAttributedStringSetAttribute(attrString,CFRangeMake(0,50),kCTForegroundColorAttributeName,red);//Createtheframesetterwiththeattributedstring.CTFramesetterRefframesetter=CTFramesetterCreateWithAttributedString(attrString);CFRelease(attrString);//CreatetheframeanddrawitintothegraphicscontextCTFrameRefframe=CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0),path,NULL);CFRelease(framesetter);CTFrameDraw(frame,context);CFRelease(frame);SimpleTextLabelsAnotherverycommontypesettingoperationisdrawingasinglelineoftexttouseasalabelforauser-interfaceelement.InCoreTextthisrequiresonlytwolinesofcode,onetocreatethelineobjectwithanattributedstringandanothertodrawthelineintoagraphiccontext.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.16 CommonOperationsColumnarLayoutListing2-2omitsinitializationoftheplaintextstring,font,andgraphicscontext,butitshowshowtocreateanattributesdictionaryanduseittocreatetheattributedstring.ToseehowtocreateaCoreTextfont,see“FontCreationandStorage”(page21).Listing2-2TypesettingasimpletextlabelCFStringRefstring;CTFontReffont;CGContextRefcontext;//Initializestring,font,andcontextCFStringRefkeys[]={kCTFontAttributeName};CFTypeRefvalues[]={font};CFDictionaryRefattributes=CFDictionaryCreate(kCFAllocatorDefault,(constvoid**)&keys,(constvoid**)&values,sizeof(keys)/sizeof(keys[0]),&kCFTypeDictionaryCallBacks,&kCFTypeDictionaryValueCallbacks);CFAttributedStringRefattrString=CFAttributedStringCreate(kCFAllocatorDefault,string,attributes);CFRelease(string);CFRelease(attributes);CTLineRefline=CTLineCreateWithAttributedString(attrString);//SettextpositionanddrawthelineintothegraphicscontextCGContextSetTextPosition(context,10.0,10.0);CTLineDraw(line,context);CFRelease(line);ColumnarLayoutLayingouttextinmultiplecolumnsisanothercommontypesettingoperation.Strictlyspeaking,CoreTextitselfonlyperformsthelayoutofonecolumnatatimeanddoesnotcalculatethecolumnsizesorlocations.YoudothoseoperationsbeforecallingCoreTexttolayoutthetextwithintherectangularpathareayou’vecalculated.Inthissample,CoreText,inadditiontolayingoutthetextineachcolumn,alsoprovidesthesubrangewithinthetextstringforeachcolumn.2010-03-03|Copyright©2010AppleInc.AllRightsReserved.17 CommonOperationsColumnarLayoutListing2-3mixesCocoamethodcallsinObjective-CwithfunctioncallsintoCarbonframeworksandCoreText.ItincludesanimplementationofthedrawRect:methodofNSView,whichcallsthelocalcreateColumnsfunction,definedfirstinthislisting.ThiscoderesidesinanNSViewsubclassinaCocoadocument-basedapplication.TheNSViewsubclassincludesanattributedStringaccessormethod,whichisnotshownherebutiscalledinthislistingtoreturntheattributedstringtobelaidout.Listing2-3Performingcolumnartextlayout-(CFArrayRef)createColumns{CGRectbounds=CGRectMake(0,0,NSWidth([selfbounds]),NSHeight([selfbounds]));intcolumn;CGRect*columnRects=(CGRect*)calloc(_columnCount,sizeof(*columnRects));//Startbysettingthefirstcolumntocovertheentireview.columnRects[0]=bounds;//Dividethecolumnsequallyacrosstheframe'swidth.CGFloatcolumnWidth=CGRectGetWidth(bounds)/_columnCount;for(column=0;column<_columnCount-1;column++){CGRectDivide(columnRects[column],&columnRects[column],&columnRects[column+1],columnWidth,CGRectMinXEdge);}//Insetallcolumnsbyafewpixelsofmargin.for(column=0;column<_columnCount;column++){columnRects[column]=CGRectInset(columnRects[column],10.0,10.0);}//Createanarrayoflayoutpaths,oneforeachcolumn.CFMutableArrayRefarray=CFArrayCreateMutable(kCFAllocatorDefault,_columnCount,&kCFTypeArrayCallBacks);for(column=0;column<_columnCount;column++){CGMutablePathRefpath=CGPathCreateMutable();CGPathAddRect(path,NULL,columnRects[column]);CFArrayInsertValueAtIndex(array,column,path);CFRelease(path);2010-03-03|Copyright©2010AppleInc.AllRightsReserved.18 CommonOperationsColumnarLayout}free(columnRects);returnarray;}-(void)drawRect:(NSRect)rect{//Drawawhitebackground.[[NSColorwhiteColor]set];[NSBezierPathfillRect:[selfbounds]];//Initializethetextmatrixtoaknownvalue.CGContextRefcontext=(CGContextRef)[[NSGraphicsContextcurrentContext]graphicsPort];CGContextSetTextMatrix(context,CGAffineTransformIdentity);CTFramesetterRefframesetter=CTFramesetterCreateWithAttributedString((CFAttributedStringRef)[selfattributedString]);CFArrayRefcolumnPaths=[selfcreateColumns];CFIndexpathCount=CFArrayGetCount(columnPaths);CFIndexstartIndex=0;intcolumn;for(column=0;column

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
关闭