Tải bản đầy đủ - 0 (trang)
Hack 61. Load New Fonts at Runtime

Hack 61. Load New Fonts at Runtime

Tải bản đầy đủ - 0trang

format(asanint),whichtodatehasnolegalvalueotherthan

Font.TRUETYPE_FONT,andanInputStream.

ThisstreamistypicallyaFileInputStreamfroma.ttfTrueTypefile,

orsomeequivalent.Byequivalent,Imeantthatyoucould

presumablyputthefontonthenetworkandgetastreamfrom

aURLorputthefontfileinsidea.jar,finditalongtheclasspath

withClassLoader.getResourceAsStream(),andloadfromthat.



MacOSX'sfontsuitcasesaholdoverfromtheClassicMacOSaren't

supported.Yourfontsneedtobein.ttffiles.



FontLoadingDemo,showninExample8-8,offersastraightforward



applicationofthisfont-loadingtechnique.Ittakesthepathtoa

.ttffileasitscommand-lineargument,createsanInputStream,

andcreatesaFont.Itthenderivesaplain,32-pointinstanceof

thefont,andusesthattoputasampleJLabelinaJFrame.



Example8-8.Loadingfontsatruntime

publicclassFontLoadingDemo{























publicstaticvoidmain(String[]args){



try{





//getfontfrompathinargs[0]





if(args.length<1){







System.out.println(







"usage:FontLoadingDemopath-to







return;





}





Filef=newFile(args[0]);





FileInputStreamin=newFileInputStrea

































FontdynamicFont=



Font.createFont(Font.TRUETYPE_

FontdynamicFont32Pt=



dynamicFont.deriveFont(32f);



























}

























}





//drawsomethingwithit



JLabeltestLabel=





newJLabel("Dynamicallyloaded





dynamicFont.getName()+"\"");



testLabel.setFont(dynamicFont32Pt);



JFrameframe=newJFrame("FontLoadin



frame.getContentPane().add(testLabel);



frame.pack();frame.setVisible(true);

}catch(Exceptione){



e.printStackTrace();

}



8.7.2.TestingFontLoading

Allyouneedtorunthisdemoisa.ttffileofaTrueTypefont,

preferablyonenotalreadyinstalledonyoursystemsoyou'll

knowthatthedemoworks.Therearemanyfreeandshareware

fontsontheWeb;IfoundtheMarriageScriptfontat

http://www.free-fonts.com/.Onceyouhavea.ttffile,runthe

demolikethis:

cadamson%javaFontLoadingDemomarriage_script.ttf



RunningthedemopopsupawindowliketheoneseeninFigure



8-6.



Figure8-6.Marriagefontloadedonthefly



Withthistechnique,andaconsistentschemeforbundlingyour

applicationresources(i.e.,stuffingallyourfontsinaJARfile,

perhapswithotherresourceslikeimages,sounds,and

localizations),youhavethefreedomtousewhateverfontsyou

likeinyourGUI,withoutworryingaboutwhatendusersdoor

don'thaveinstalled.



Hack62.BuildaColorfulVector-BasedButton



Buildaresolution-independentOSX-stylebuttonusing

scalablegraphicscode.

Thebuttoninthishackisresolutionindependent,meaningthat

itcanresizeandrescaleautomaticallyastheuser'swindows

anddisplaychange,stretchingandtilingthegraphicstofillthe

newspace.Thebuttondoesn'tdependonbeinganyparticular

sizetolookgood.Ashigher-qualityandhigherresolution

monitorsbecomemorecommon,userswillstarttoexpect

attractiveinterfacesthatscaleandreflowwiththeirincreasingly

expansivedisplays.Thishackshowshowtocreateanattractive

JButtonthatwillscalewithbothsizeandresolution,openingthe

doorforacompletelyvectordrawnSwingLookandFeel.



8.8.1.UseScalingtoYourAdvantage

Sincethisbuttonmustscalewiththesizeofthescreen,you

canuseavariablecalledscale.Everypieceofdrawingcodefor

thisbuttonisdonerelativetoscale'svalue.Ifthescalevalue

changes,theentirebuttonwillchangeaccordingly.Thescale

valueitselfisbasedonthecurrentfontsizeofthecomponent.

Ifthecomponent'sfontisresized(duetoaDPIchange,for

example),thenthescalevaluewillchangeaccordingly,resizing

theentirebutton.Withascalevalueinplace,thishackis

simplyamatterofrecreatingtheAquabuttonlookwithJava2D

calls.ThegoalisabuttonthatlookslikeFigure8-7.



Figure8-7.AgreenvectorJButton



Notasimpletask,butit'snotimpossibleeither.Alltheworkis

doneinExample8-9.



Example8-9.Creatingliquidbuttons



publicclassVectorButtonextendsJButtonimplementsMouseListe



publicVectorButton(){





this.addMouseListener(this);



}

publicDimensiongetPreferredSize(){





Stringtext=getText();





FontMetricsfm=this.getFontMetrics(getFont())





floatscale=(50f/30f)*this.getFont().getSize2





intw=fm.stringWidth(text);





w+=(int)(scale*1.4f);





inth=fm.getHeight();





h+=(int)(scale*.3f);





returnnewDimension(w,h);



}



publicvoidpaintComponent(Graphicsg){





Graphics2Dg2=(Graphics2D)g;





g2.setRenderingHint(RenderingHints.KEY_ANTIALIA







RenderingHints.VALUE_ANTIALIAS_ON);





g2.setColor(this.getBackground());





g2.fillRect(0,0,this.getWidth(),this.getHeight(









floatscale=(50f/30f)*this.getFont().getSize2











drawLiquidButton(this.getForeground(),



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 61. Load New Fonts at Runtime

Tải bản đầy đủ ngay(0 tr)

×