Android的字样createFromAsset字样、Android、createFromAsset

2023-09-07 15:41:53 作者:晨晓破幽冥

我有一个自定义视图其中提请文本到画布上。我想将字体更改为存储在资产文件夹中的字体。

I Have a Custom View which draws text onto the Canvas. I want to change the Font to a font stored in assets folder.

我使用Android的工作室,所以我创建了一个文件夹的src / main /资产,并放置在那里我的ttf文件。

I am using Android Studio so I created a folder src/main/assets and placed my ttf files in there.

Paint txt = new Paint()
Typeface font = Typeface.createFromAsset(getAssets(), "robotobold.ttf");
txt.setTypeface(font);

问题的是Android Studio不承认getAssets()内我的自定义视图,但它承认它在我里面的活动。我试图从我的活动,通过传递字样,但是当我这样做,它不会更改字体。

Problem is Android Studio doesn't recognize getAssets() inside my Custom View, however it recognizes it inside my Activity. I have tried passing Typeface through from my Activity but when I do it it doesn't change the font.

推荐答案

您可以使用查看的getContext()方法来获得当前上下文,然后用它来获得的资产的:

You can use your View's getContext() method to get the current Context, then use it to get the assets:

Typeface font = Typeface.createFromAsset(getContext().getAssets(), "robotobold.ttf");