首页 > 代码库 > Java字体优化

Java字体优化

需求背景

最近在做的项目显示的字体感觉太丑,于是乎想着DIY改进一下。

查阅资料,总觉得别人写的都不咋地,于是决心写一篇略微完善点的关于项目字体优化方面的文章。

当然,这篇文章不会教你如何使用TrueType去创建属于你自己的字体,而是使用现成的字体库。

读取、使用系统字体回顾

读取系统字体的字体名字体数量

方法1: 使用GraphicsEnvironment类

  • 获取所有字体的family
package com.forget406.study;import java.awt.GraphicsEnvironment;public class CustomeFontReading {    public static void main(String[] args) {        String[] fonts =             GraphicsEnvironment  // GraphicsEnvironment(抽象类)  图形环境类                .getLocalGraphicsEnvironment()  // 获取本地图形环境                    .getAvailableFontFamilyNames();  // 获取可用字体family名                int fontCount = 0;   // 字体数统计        for(String font : fonts) {            fontCount ++;            System.out.println(font);        }        System.out.println("系统字体数:" + fontCount);    }}
技术分享
Agency FBAlgerianArialArial BlackArial NarrowArial Rounded MT BoldArial Unicode MSArvoBaskerville Old FaceBauhaus 93Bell MTBerlin Sans FBBerlin Sans FB DemiBernard MT CondensedBlackadder ITCBodoni MTBodoni MT BlackBodoni MT CondensedBodoni MT Poster CompressedBook AntiquaBookman Old StyleBookshelf Symbol 7Bradley Hand ITCBritannic BoldBroadwayBrush Script MTCalibriCalibri LightCalifornian FBCalisto MTCambriaCambria MathCandaraCastellarCentaurCenturyCentury GothicCentury SchoolbookChillerColonna MTComic Sans MSConsolasConstantiaCooper BlackCopperplate Gothic BoldCopperplate Gothic LightCorbelCourier NewCurlz MTDialogDialogInputDroid SerifEbrimaEdwardian Script ITCElephantEngravers MTEras Bold ITCEras Demi ITCEras Light ITCEras Medium ITCEuclidEuclid ExtraEuclid FrakturEuclid Math OneEuclid Math TwoEuclid SymbolFelix TitlingFencesFootlight MT LightForteFranklin Gothic BookFranklin Gothic DemiFranklin Gothic Demi CondFranklin Gothic HeavyFranklin Gothic MediumFranklin Gothic Medium CondFreestyle ScriptFrench Script MTGabriolaGadugiGaramondGeorgiaGigiGill Sans MTGill Sans MT CondensedGill Sans MT Ext Condensed BoldGill Sans Ultra BoldGill Sans Ultra Bold CondensedGloucester MT Extra CondensedGoudy Old StyleGoudy StoutHaettenschweilerHarlow Solid ItalicHarringtonHigh Tower TextImpactImprint MT ShadowIndie FlowerInformal RomanJavanese TextJokermanJuice ITCKristen ITCKunstler ScriptLeelawadee UILeelawadee UI SemilightLobsterLucida BrightLucida CalligraphyLucida ConsoleLucida FaxLucida HandwritingLucida SansLucida Sans TypewriterLucida Sans UnicodeMagnetoMaiandra GDMalgun GothicMalgun Gothic SemilightMarlettMatura MT Script CapitalsMeiryoMeiryo UIMicrosoft HimalayaMicrosoft JhengHeiMicrosoft JhengHei LightMicrosoft JhengHei UIMicrosoft JhengHei UI LightMicrosoft MHeiMicrosoft NeoGothicMicrosoft New Tai LueMicrosoft PhagsPaMicrosoft Sans SerifMicrosoft Tai LeMicrosoft YaHei UIMicrosoft YaHei UI LightMicrosoft Yi BaitiMingLiU-ExtBMingLiU_HKSCS-ExtBMistralModern No. 20Mongolian BaitiMonospacedMonotype CorsivaMS GothicMS OutlookMS PGothicMS Reference Sans SerifMS Reference SpecialtyMS UI GothicMT ExtraMT Extra TigerMV BoliMyanmar TextNiagara EngravedNiagara SolidNirmala UINirmala UI SemilightOCR A ExtendedOld English Text MTOnyxOpen SansPalace Script MTPalatino LinotypePapyrusParchmentPerpetuaPerpetua Titling MTPlaybillPMingLiU-ExtBPoiret OnePoor RichardPristinaRage ItalicRalewayRavieRobotoRoboto CondensedRoboto SlabRockwellRockwell CondensedRockwell Extra BoldSansSerifScript MT BoldSegoe MDL2 AssetsSegoe PrintSegoe ScriptSegoe UISegoe UI BlackSegoe UI EmojiSegoe UI HistoricSegoe UI LightSegoe UI SemiboldSegoe UI SemilightSegoe UI SymbolSegoe WPSegoe WP BlackSegoe WP LightSegoe WP SemiboldSegoe WP SemiLightSerifShowcard GothicSimSun-ExtBSitka BannerSitka DisplaySitka HeadingSitka SmallSitka SubheadingSitka TextSnap ITCStencilSylfaenSymbolSymbol TigerSymbol Tiger ExpertTahomaTempus Sans ITCTigerTiger ExpertTimes New RomanTrebuchet MSTw Cen MTTw Cen MT CondensedTw Cen MT Condensed Extra BoldVerdanaViner Hand ITCVivaldiVladimir ScriptWebdingsWide LatinWingdingsWingdings 2Wingdings 3woziku-wfzt-CN4262Yu GothicYu Gothic LightYu Gothic MediumYu Gothic UIYu Gothic UI LightYu Gothic UI SemiboldYu Gothic UI Semilight仿宋华文中宋华文仿宋华文宋体华文彩云华文新魏华文楷体华文琥珀华文细黑华文行楷华文隶书宋体幼圆微软雅黑微软雅黑 Light我字酷无非字体新宋体方正兰亭超细黑简体方正姚体方正等线方正舒体楷体等线等线 Light隶书黑体系统字体数:267
程序运行结果
  • 获取所有字体的名字
package com.forget406.study;import java.awt.Font;import java.awt.GraphicsEnvironment;public class CustomeFontReading4 {    public static void main(String[] args) {                Font[] fonts = GraphicsEnvironment            .getLocalGraphicsEnvironment()                .getAllFonts();        for (Font font : fonts) {            System.out.println(font.getFontName());        }
System.out.println("字体数量:" + fonts.length); }}
技术分享
Agency FBAgency FB BoldAlgerianArialArial BlackArial BoldArial Bold ItalicArial ItalicArial NarrowArial Narrow BoldArial Narrow Bold ItalicArial Narrow ItalicArial Rounded MT BoldArial Unicode MSArvo BoldArvo BoldArvo Bold ItalicArvo-ItalicBaskerville Old FaceBauhaus 93Bell MTBell MT BoldBell MT ItalicBerlin Sans FBBerlin Sans FB BoldBerlin Sans FB Demi BoldBernard MT CondensedBlackadder ITCBodoni MTBodoni MT BlackBodoni MT Black ItalicBodoni MT BoldBodoni MT Bold ItalicBodoni MT CondensedBodoni MT Condensed BoldBodoni MT Condensed Bold ItalicBodoni MT Condensed ItalicBodoni MT ItalicBodoni MT Poster CompressedBook AntiquaBook Antiqua BoldBook Antiqua Bold ItalicBook Antiqua ItalicBookman Old StyleBookman Old Style BoldBookman Old Style Bold ItalicBookman Old Style ItalicBookshelf Symbol 7Bradley Hand ITCBritannic BoldBroadwayBrush Script MT ItalicCalibriCalibri BoldCalibri Bold ItalicCalibri ItalicCalibri LightCalibri Light ItalicCalifornian FBCalifornian FB BoldCalifornian FB ItalicCalisto MTCalisto MT BoldCalisto MT Bold ItalicCalisto MT ItalicCambriaCambria BoldCambria Bold ItalicCambria ItalicCambria MathCandaraCandara BoldCandara Bold ItalicCandara ItalicCastellarCentaurCenturyCentury GothicCentury Gothic BoldCentury Gothic Bold ItalicCentury Gothic ItalicCentury SchoolbookCentury Schoolbook BoldCentury Schoolbook Bold ItalicCentury Schoolbook ItalicChillerColonna MTComic Sans MSComic Sans MS BoldComic Sans MS Bold ItalicComic Sans MS ItalicConsolasConsolas BoldConsolas Bold ItalicConsolas ItalicConstantiaConstantia BoldConstantia Bold ItalicConstantia ItalicCooper BlackCopperplate Gothic BoldCopperplate Gothic LightCorbelCorbel BoldCorbel Bold ItalicCorbel ItalicCourier NewCourier New BoldCourier New Bold ItalicCourier New ItalicCurlz MTDialog.boldDialog.bolditalicDialog.italicDialog.plainDialogInput.boldDialogInput.bolditalicDialogInput.italicDialogInput.plainDroid Serif BoldDroid Serif BoldDroid Serif Bold ItalicDroid Serif ItalicEbrimaEbrima BoldEdwardian Script ITCElephantElephant ItalicEngravers MTEras Bold ITCEras Demi ITCEras Light ITCEras Medium ITCEuclidEuclid BoldEuclid Bold ItalicEuclid ExtraEuclid Extra BoldEuclid FrakturEuclid Fraktur BoldEuclid ItalicEuclid Math OneEuclid Math One BoldEuclid Math TwoEuclid Math Two BoldEuclid SymbolEuclid Symbol BoldEuclid Symbol Bold ItalicEuclid Symbol ItalicFelix TitlingFences PlainFootlight MT LightForteFranklin Gothic BookFranklin Gothic Book ItalicFranklin Gothic DemiFranklin Gothic Demi CondFranklin Gothic Demi ItalicFranklin Gothic HeavyFranklin Gothic Heavy ItalicFranklin Gothic MediumFranklin Gothic Medium CondFranklin Gothic Medium ItalicFreestyle ScriptFrench Script MTGabriolaGadugiGadugi BoldGaramondGaramond BoldGaramond ItalicGeorgiaGeorgia BoldGeorgia Bold ItalicGeorgia ItalicGigiGill Sans MTGill Sans MT BoldGill Sans MT Bold ItalicGill Sans MT CondensedGill Sans MT Ext Condensed BoldGill Sans MT ItalicGill Sans Ultra BoldGill Sans Ultra Bold CondensedGloucester MT Extra CondensedGoudy Old StyleGoudy Old Style BoldGoudy Old Style ItalicGoudy StoutHaettenschweilerHarlow Solid ItalicHarringtonHigh Tower TextHigh Tower Text ItalicImpactImprint MT ShadowIndie FlowerInformal RomanJavanese TextJokermanJuice ITCKristen ITCKunstler ScriptLeelawadee UILeelawadee UI BoldLeelawadee UI SemilightLobsterLucida Bright RegularLucida Bright DemiboldLucida Bright Demibold ItalicLucida Bright ItalicLucida Bright RegularLucida Calligraphy ItalicLucida ConsoleLucida Fax DemiboldLucida Fax Demibold ItalicLucida Fax ItalicLucida Fax RegularLucida Handwriting ItalicLucida Sans DemiboldLucida Sans DemiboldLucida Sans Demibold RomanLucida Sans ItalicLucida Sans RegularLucida Sans Typewriter BoldLucida Sans Typewriter BoldLucida Sans Typewriter ObliqueLucida Sans Typewriter RegularLucida Sans UnicodeMS GothicMS OutlookMS PGothicMS Reference Sans SerifMS Reference SpecialtyMS UI GothicMT ExtraMT Extra TigerMV BoliMagneto BoldMaiandra GDMalgun GothicMalgun Gothic BoldMalgun Gothic SemilightMarlettMatura MT Script CapitalsMeiryoMeiryo BoldMeiryo Bold ItalicMeiryo ItalicMeiryo UIMeiryo UI BoldMeiryo UI Bold ItalicMeiryo UI ItalicMicrosoft HimalayaMicrosoft JhengHeiMicrosoft JhengHei BoldMicrosoft JhengHei LightMicrosoft JhengHei UIMicrosoft JhengHei UI BoldMicrosoft JhengHei UI LightMicrosoft MHeiMicrosoft MHei BoldMicrosoft NeoGothicMicrosoft NeoGothic BoldMicrosoft New Tai LueMicrosoft New Tai Lue BoldMicrosoft PhagsPaMicrosoft PhagsPa BoldMicrosoft Sans SerifMicrosoft Tai LeMicrosoft Tai Le BoldMicrosoft YaHei UI LightMicrosoft Yahei UIMicrosoft Yahei UI BoldMicrosoft Yi BaitiMingLiU-ExtBMingLiU_HKSCS-ExtBMistralModern No. 20Mongolian BaitiMonospaced.boldMonospaced.bolditalicMonospaced.italicMonospaced.plainMonotype CorsivaMyanmar TextMyanmar Text Bold新宋体Niagara EngravedNiagara SolidNirmala UINirmala UI BoldNirmala UI SemilightOCR A ExtendedOld English Text MTOnyxOpen Sans BoldOpen Sans BoldOpen Sans Bold ItalicOpen Sans ItalicPMingLiU-ExtBPalace Script MTPalatino LinotypePalatino Linotype BoldPalatino Linotype Bold ItalicPalatino Linotype ItalicPapyrusParchmentPerpetuaPerpetua BoldPerpetua Bold ItalicPerpetua ItalicPerpetua Titling MT BoldPerpetua Titling MT LightPlaybillPoiret OnePoor RichardPristinaRage ItalicRaleway BoldRaleway BoldRavieRoboto BoldRoboto BoldRoboto Bold ItalicRoboto Condensed BoldRoboto Condensed BoldRoboto Condensed Bold ItalicRoboto Condensed ItalicRoboto ItalicRoboto Slab BoldRoboto Slab RegularRockwellRockwell BoldRockwell Bold ItalicRockwell CondensedRockwell Condensed BoldRockwell Extra BoldRockwell ItalicSansSerif.boldSansSerif.bolditalicSansSerif.italicSansSerif.plainScript MT BoldSegoe MDL2 AssetsSegoe PrintSegoe Print BoldSegoe ScriptSegoe Script BoldSegoe UISegoe UI BlackSegoe UI Black ItalicSegoe UI BoldSegoe UI Bold ItalicSegoe UI EmojiSegoe UI HistoricSegoe UI ItalicSegoe UI LightSegoe UI Light ItalicSegoe UI SemiboldSegoe UI Semibold ItalicSegoe UI SemilightSegoe UI Semilight ItalicSegoe UI SymbolSegoe WPSegoe WP BlackSegoe WP BoldSegoe WP LightSegoe WP SemiLightSegoe WP SemiboldSerif.boldSerif.bolditalicSerif.italicSerif.plainShowcard Gothic宋体SimSun-ExtBSitka BannerSitka Banner BoldSitka Banner Bold ItalicSitka Banner ItalicSitka DisplaySitka Display BoldSitka Display Bold ItalicSitka Display ItalicSitka HeadingSitka Heading BoldSitka Heading Bold ItalicSitka Heading ItalicSitka SmallSitka Small BoldSitka Small Bold ItalicSitka Small ItalicSitka SubheadingSitka Subheading BoldSitka Subheading Bold ItalicSitka Subheading ItalicSitka TextSitka Text BoldSitka Text Bold ItalicSitka Text ItalicSnap ITCStencilSylfaenSymbolSymbol TigerSymbol Tiger ExpertTahomaTahoma BoldTempus Sans ITCTigerTiger ExpertTimes New RomanTimes New Roman BoldTimes New Roman Bold ItalicTimes New Roman ItalicTrebuchet MSTrebuchet MS BoldTrebuchet MS Bold ItalicTrebuchet MS ItalicTw Cen MTTw Cen MT BoldTw Cen MT Bold ItalicTw Cen MT CondensedTw Cen MT Condensed BoldTw Cen MT Condensed Extra BoldTw Cen MT ItalicVerdanaVerdana BoldVerdana Bold ItalicVerdana ItalicViner Hand ITCVivaldi ItalicVladimir ScriptWebdingsWide LatinWingdingsWingdings 2Wingdings 3Yu Gothic BoldYu Gothic LightYu Gothic MediumYu Gothic RegularYu Gothic UI BoldYu Gothic UI LightYu Gothic UI RegularYu Gothic UI SemiboldYu Gothic UI SemilightYuGothicYuGothic Bold我字酷无非字体仿宋华文中宋华文仿宋华文宋体华文彩云华文新魏华文楷体华文琥珀华文细黑华文行楷华文隶书宋体幼圆微软雅黑微软雅黑 Bold微软雅黑 Light我字酷无非字体新宋体方正兰亭超细黑简体方正姚体方正等线 Regular方正舒体楷体方正等线 Regular等线 Bold等线 Light隶书黑体字体数量:479
程序运行结果

以上两段代码有细微的区别,根本原因在于:

所见字体文件中包含多个字体子文件 。如下图所示,左侧简体字又分成:常规、粗体、细体,即包含右侧的字体。

  技术分享         技术分享  

方法2: 调用核心类库的文件操作API

  • 过滤字体文件
package com.forget406.study;import java.io.File;import java.io.FileFilter;public class CustomeFontReading2 {    public static void main(String[] args) {        // windows10 系统字体库目录        File file = new File("C:" +             File.separator+"Windows"+                File.separator+"Fonts"            );        // 文件信息判断        if (file.exists()) {            if (file.isDirectory()) {                System.out.println("该路径为文件夹");                                // 获取目录下所有以".ttf"(True Type Font)结尾的文件                File[] fontFile = file.listFiles(new FileFilter() {                    // 过滤出名字符合要求的文件                    @Override                    public boolean accept(File file) {                        return file.getName().endsWith(".");                    }                                    });                                // 输出所有字体文件名(截去后缀)                for(File font : fontFile) {                    String name = font.getName();                    int suffixIndex = name.lastIndexOf(".ttf");                    System.out.println(name.substring(0, suffixIndex));                }                System.out.println("字体数量:" + fontFile.length);            } else if (file.isFile()){                System.out.println("该路径为文件");            } else {                System.out.println("貌似没有别的可能了");            }            System.out.println(file.getName());        } else {            System.out.println("文件路径不存在");        }            }}
技术分享
该路径为文件夹arialarialbdarialbiarialiariblkArvo-BoldArvo-BoldItalicArvo-ItalicArvo-RegularcalibricalibribcalibriicalibrilcalibrilicalibrizcambriabcambriaicambriazCandaraCandarabCandaraiCandarazcomiccomicbdcomicicomiczconsolaconsolabconsolaiconsolazconstanconstanbconstaniconstanzcorbelcorbelbcorbelicorbelzcourcourbdcourbicouriDengDengbDenglDengXianDroidSerif-BoldDroidSerif-BoldItalicDroidSerif-ItalicDroidSerifebrimaebrimabdeuclideuclidbeuclidbieuclidieucsymeucsymbeucsymbieucsymieuextraeuextrabeufrakeufrakbeumat1eumat1beumat2eumat2bfencesframdframditGabriolagadugigadugibgeorgiageorgiabgeorgiaigeorgiazhimalayaimpactIndieFlowerjavatextLeelaUIbLeelawUILeelUIslLobster-Regularluconl_10646malgunmalgunbdmalgunslmarlettmicrossmmrtextmmrtextbmonbaitiMSMHei-BoldMSMHeiMSNeoGothic-BoldMSNeoGothicmsyiMt Extra TigermtextramvboliNirmalaNirmalaBNirmalaSntailuntailubOpenSans-BoldOpenSans-BoldItalicOpenSans-ItalicOpenSans-RegularpalapalabpalabipalaiphagspaphagspabPoiretOne-RegularRaleway-BoldRaleway-RegularRoboto-BoldRoboto-BoldItalicRoboto-ItalicRoboto-RegularRobotoCondensed-BoldRobotoCondensed-BoldItalicRobotoCondensed-ItalicRobotoCondensed-RegularRobotoSlab-BoldRobotoSlab-Regularsegmdl2segoeprsegoeprbsegoescsegoescbsegoeuisegoeuibsegoeuiisegoeuilsegoeuislsegoeuizSegoeWP-BlackSegoeWP-BoldSegoeWP-LightSegoeWP-SemiboldSegoeWP-SemilightSegoeWPseguiblseguibliseguiemjseguihisseguiliseguisbseguisbiseguisliseguisymsimfangsimheisimkaisimsunbsylfaenSymbol Tiger ExpertSymbol TigersymboltahomatahomabdtailetailebTiger ExpertTigertimestimesbdtimesbitimesitrebuctrebucbdtrebucbitrebucitverdanaverdanabverdanaiverdanazwebdingswingdingYuGothic-BoldYuGothic我字酷无非字体我字酷无非字体_0我字酷无非字体_1字体数量:191
程序运行结果

注意:windows 10系统中字体文件后缀(suffix)含有三种:ttf、.TTF、.ttc、fon。

  • 不过滤字体文件

由于c:\Windows\Font文件夹下除字体文件外不含其它形式文件,因此可以不对文件结果进行过滤。

package com.forget406.study;import java.io.File;import java.io.FileFilter;public class CustomeFontReading3 {    public static void main(String[] args) {        // windows10 系统字体库目录        File file = new File("C:" +             File.separator+"Windows"+                File.separator+"Fonts"            );        // 文件信息判断        if (file.exists()) {            if (file.isDirectory()) {                File[] fontFile = file.listFiles();                for(File font : fontFile) {                    String name = font.getName();                    int suffixIndex = name.lastIndexOf(".");                    System.out.println(name.substring(0, suffixIndex));                }                System.out.println("字体数量:" + fontFile.length);            } else if (file.isFile()){                System.out.println("该路径为文件");            } else {                System.out.println("貌似没有别的可能了");            }        } else {            System.out.println("文件路径不存在");        }            }}
技术分享
该路径为文件夹8514fix8514fixe8514fixg8514fixr8514fixt8514oem8514oeme8514oemg8514oemr8514oemt8514sys8514syse8514sysg8514sysr8514syst857758585585f125585f125685f125785f87485s125585s125685s125785s874AGENCYBAGENCYRALGERANTQUABANTQUABIANTQUAIapp775app850app852app855app857app866app932app936app949app950arialarialbdarialbiarialiARIALNARIALNBARIALNBIARIALNIARIALUNIariblkARLRDBDArvo-BoldArvo-BoldItalicArvo-ItalicArvo-RegularBASKVILLBAUHS93BELLBELLBBELLIBERNHCBKANTBOD_BBOD_BIBOD_BLAIBOD_BLARBOD_CBBOD_CBIBOD_CIBOD_CRBOD_IBOD_PSTCBOD_RBOOKOSBOOKOSBBOOKOSBIBOOKOSIBRADHITCBRITANICBRLNSBBRLNSDBBRLNSRBROADWBRUSHSCIBSSYM7c8514fixc8514oemc8514syscalibricalibribcalibriicalibrilcalibrilicalibrizCALIFBCALIFICALIFRCALISTCALISTBCALISTBICALISTIcambriacambriabcambriaicambriazCandaraCandarabCandaraiCandarazCASTELARCENSCBKCENTAURCENTURYcga40737cga40850cga40852cga40857cga40866cga40869cga40woacga80737cga80850cga80852cga80857cga80866cga80869cga80woaCHILLERCOLONNAcomiccomicbdcomicicomiczconsolaconsolabconsolaiconsolazconstanconstanbconstaniconstanzCOOPBLCOPRGTBCOPRGTLcorbelcorbelbcorbelicorbelzcoue1255coue1256coue1257couf1255couf1256couf1257courcourbdcourbicourecoureecouregcourercouretcourfcourfecourfgcourfrcourftcouriCURLZ___cvgafixcvgasysDengDengbDenglDengXiandesktopdos737dos869dosappDroidSerif-BoldDroidSerif-BoldItalicDroidSerif-ItalicDroidSerifebrimaebrimabdega40737ega40850ega40852ega40857ega40866ega40869ega40woaega80737ega80850ega80852ega80857ega80866ega80869ega80woaELEPHNTELEPHNTIENGRERASBDERASDEMIERASLGHTERASMDeuclideuclidbeuclidbieuclidieucsymeucsymbeucsymbieucsymieuextraeuextrabeufrakeufrakbeumat1eumat1beumat2eumat2bFELIXTIfencesfms_metadataFORTEFRABKFRABKITFRADMFRADMCNFRADMITFRAHVFRAHVITframdFRAMDCNframditFREESCPTFRSCRIPTFTLTLTFZLTCXHJWFZSTKFZYTKGabriolagadugigadugibGARAGARABDGARAITgeorgiageorgiabgeorgiaigeorgiazGIGIGILBI___GILB____GILC____GILI____GILLUBCDGILSANUBGIL_____GLECBGlobalMonospaceGlobalSansSerifGlobalSerifGlobalUserInterfaceGLSNECBGOTHICGOTHICBGOTHICBIGOTHICIGOUDOSGOUDOSBGOUDOSIGOUDYSTOh8514fixh8514oemh8514sysHARLOWSIHARNGTONHATTENhimalayaHTOWERTHTOWERTIhvgafixhvgasysimpactIMPRISHAIndieFlowerINFROMANITCBLKADITCEDSCRITCKRISTj8514fixj8514oemj8514sysjavatextJOKERMANjsmallejsmallfJUICE___jvgafixjvgasysKUNSTLERLATINWDLBRITELBRITEDLBRITEDILBRITEILCALLIGLeelaUIbLeelawUILeelUIslLFAXLFAXDLFAXDILFAXILHANDWLobster-RegularLSANSLSANSDLSANSDILSANSILTYPELTYPEBLTYPEBOLTYPEOluconl_10646MAGNETOBMAIANmalgunmalgunbdmalgunslmarlettMATURASCMEIRYOMEIRYOBmicrossmingliubMISTRALmmrtextmmrtextbMOD20modernmonbaitimsgothicmsjhmsjhbdmsjhlMSMHei-BoldMSMHeiMSNeoGothic-BoldMSNeoGothicmsyhmsyhbdmsyhlmsyiMt Extra TigerMTCORSVAmtextramvboliNIAGENGNIAGSOLNirmalaNirmalaBNirmalaSntailuntailubOCRAEXTOLDENGLONYXOpenSans-BoldOpenSans-BoldItalicOpenSans-ItalicOpenSans-RegularOUTLOOKpalapalabpalabipalaiPALSCRIPAPYRUSPARCHMPERBI___PERB____PERI____PERTIBDPERTILIPER_____phagspaphagspabPLAYBILLPoiretOne-RegularPOORICHPRISTINARAGERaleway-BoldRaleway-RegularRAVIEREFSANREFSPCLRoboto-BoldRoboto-BoldItalicRoboto-ItalicRoboto-RegularRobotoCondensed-BoldRobotoCondensed-BoldItalicRobotoCondensed-ItalicRobotoCondensed-RegularRobotoSlab-BoldRobotoSlab-RegularROCCB___ROCC____ROCKROCKBROCKBIROCKEBROCKIromans8514fixs8514oems8514sysSCHLBKBSCHLBKBISCHLBKIscriptSCRIPTBLsegmdl2segoeprsegoeprbsegoescsegoescbsegoeuisegoeuibsegoeuiisegoeuilsegoeuislsegoeuizSegoeWP-BlackSegoeWP-BoldSegoeWP-LightSegoeWP-SemiboldSegoeWP-SemilightSegoeWPseguiblseguibliseguiemjseguihisseguiliseguisbseguisbiseguisliseguisymsere1255sere1256sere1257serf1255serf1256serf1257serifeserifeeserifegseriferserifetseriffseriffeseriffgseriffrserifftSHOWGsimfangsimheisimkaiSIMLIsimsunsimsunbSIMYOUSitkaSitkaBSitkaISitkaZsmae1255smae1256smae1257smaf1255smaf1256smaf1257smallesmalleesmallegsmallersmalletsmallfsmallfesmallfgsmallfrsmallftSNAP____ssee1255ssee1256ssee1257ssee874ssef1255ssef1256ssef1257ssef874sserifesserifeesserifegsserifersserifetsseriffsseriffesseriffgsseriffrsserifftStaticCacheSTCAIYUNSTENCILSTFANGSOSTHUPOSTKAITISTLITISTSONGSTXIHEISTXINGKASTXINWEISTZHONGSsvgafixsvgasyssylfaenSymbol Tiger ExpertSymbol TigersymboltahomatahomabdtailetailebTCBI____TCB_____TCCB____TCCEBTCCM____TCMI____TCM_____TEMPSITCTiger ExpertTigertimestimesbdtimesbitimesitrebuctrebucbdtrebucbitrebucitverdanaverdanabverdanaiverdanazvga737vga775vga850vga852vga855vga857vga860vga861vga863vga865vga866vga869vga932vga936vga949vga950vgaf1255vgaf1256vgaf1257vgaf874vgafixvgafixevgafixgvgafixrvgafixtvgaoemvgas1255vgas1256vgas1257vgas874vgasysvgasysevgasysgvgasysrvgasystVINERITCVIVALDIIVLADIMIRwebdingswingdingWINGDNG2WINGDNG3YuGothBYuGothic-BoldYuGothicYuGothLYuGothMYuGothR我字酷无非字体我字酷无非字体_0我字酷无非字体_1字体数量:612
程序运行结果

系统字体名字都用英文字母表示(不含中文)。自定义字体安装到操作系统中根据实际取名情况而定。

技术分享

比较两种方式的区别 

GraphicsEnvironment类实现对字体(常规、粗细、斜体等)封装,即粗略分类读取系统字体Java推荐
核心类库文件操作API读取所有字体文件,即详细分类(包含.fon字体文件)读取系统字体时不推荐

使用系统字体在屏幕显示 

package com.forget406.study;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.WindowConstants;public class CustomeFontReading extends JFrame {    public CustomeFontReading() {        setTitle("自定义字体使用");        setSize(300, 400);        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        setVisible(true);            MyPanel panel = new MyPanel();        add(panel);    }        public static void main(String[] args) {        new CustomeFontReading();            }}class MyPanel extends JPanel {        @Override    public void paint(Graphics g) {        g.setColor(Color.BLUE);        g.setFont(new Font("楷体", Font.BOLD, 50));        g.drawString("和谐社会", 30, 200);    }}

程序运行结果

技术分享

将自定义字体导入系统字体库,也能够通过这种方法使用自定义字体。

引入外部自定义字体

字体下载网站传送门 

 【分享】全球最大的字体下载网站:www.fontke.com(字客网)

创建、注册外部字体 

以自己项目中使用过的字体文件Deeko Comic Regular.ttf为例,加以说明。以下是此字体对应的参数说明。

技术分享技术分享

在使用外部字体时,必须先创建字体,然后在操作系统中注册外部字体;否则无法使用外部字体。

package com.forget406.study;import java.awt.Color;import java.awt.Font;import java.awt.FontFormatException;import java.awt.Graphics;import java.awt.GraphicsEnvironment;import java.io.File;import java.io.IOException;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.WindowConstants;public class CustomeFontReading extends JFrame {        private static final long serialVersionUID = 270583473364792225L;    public CustomeFontReading() {        setTitle("自定义字体使用");        setSize(300, 400);        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        setVisible(true);            MyPanel panel = new MyPanel();        add(panel);    }        public static void main(String[] args) {        new CustomeFontReading();       }}class MyPanel extends JPanel {        private static final long serialVersionUID = 4897720234933257563L;        @Override    public void paint(Graphics g) {        g.setColor(Color.BLUE);        registerCustomeFont("Deeko Comic Regular.ttf");
     // 画笔使用自定义字体(字体风格、尺寸可与创建时参数不同) g.setFont(
new Font("Deeko Comic Regular", Font.BOLD, 30)); g.drawString("HARMONY", 30, 200); } private void registerCustomeFont(String filename) { File fontFile = new File( "font"+File.separator+filename); System.out.println(fontFile.exists()); Font font = null; try {
       // 创建自定义字体 font
= Font.createFont( Font.TRUETYPE_FONT, fontFile); // 字体.ttf格式 // 设置字体风格、尺寸
       font.deriveFont(Font.BOLD,30F); GraphicsEnvironment ge
= // 获得本地图形环境对象 GraphicsEnvironment .getLocalGraphicsEnvironment();
       // 在本地图形环境中注册当前字体
boolean register = ge.registerFont(font); if(register) { System.out.println("注册字体成功"); } else { System.out.println("注册字体失败"); } System.out.println("外部字体创建成功"); } catch (FontFormatException e) { e.printStackTrace(); System.out.println("字体格式化异常"); } catch (IOException e) { e.printStackTrace(); System.out.println("读写字体文件异常"); } }}

程序测试结果

技术分享 

除了使用File,还能够使用InputStream。但就性能而言,推荐使用File。

技术分享

Java字体优化