简体   繁体   English

在Android上使用自定义字体

[英]Using custom fonts on Android

I'm trying to load a custom font as follows: 我正在尝试加载自定义字体,如下所示:

private Paint customFont18;
customFont18 = new Paint();
customFont18.setTextSize(18);
Typeface fontFace = Typeface.createFromAsset(getAssets(), "FONT.TTF"); 
customFont18.setTypeface(fontFace);

The getAssets fails, thows this: getAssets失败了,这个:

-The method getAssets() is undefined for the type MyClass
-assetManager cannot be resolved to a variable

What is my problem? 我的问题是什么? I've seen several examples like this but none works in my case. 我见过几个这样的例子,但在我的情况下都没有。 Thanks in advance. 提前致谢。

getAssets() is a method of Context. getAssets()是Context的一种方法。 If your class is not an activity, you'll need to pass a context into it and then call getAssets() on that. 如果您的类不是活动,则需要将上下文传递给它,然后在其上调用getAssets()

public myClass(Context myContext) {
    Typeface typeface = Typeface.createFromAsset(myContext.getAssets(), "FONT.TTF");
    ...
}

尝试改变这样:

Typeface fontFace = Typeface.createFromAsset(getAssets(), "fonts/FONT.TTF");

Use simple EasyFonts third party library to set variety of custom font to your TextView . 使用简单的EasyFonts第三方库为TextView设置各种自定义字体。 By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. 通过使用此库,您不必担心下载和添加字体到assets / fonts文件夹。 Also about Typeface object creation. 还有关于字体对象的创建。

Simply: 只是:

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));

This library also provides variety of font faces. 该库还提供各种字体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM