1

我正在尝试实现一个使用我自己的自定义字体的自定义文本视图。

有没有办法在做 Super.onDraw() 之前设置字体?

以便将常用字体替换为我要使用的自定义字体。

就像是:

protected void onDraw(Canvas canvas)
{
    Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfonts.ttf");
    this.setTypeface(font1);
    this.setTextSize(18);
    super.onDraw(canvas);
}

我知道上面的代码行不通。

还是我别无选择,只能使用 drawText() 这样做?

4

3 回答 3

9

每次调用 onDraw 方法时都创建新的 Typeface 对象是一种非常糟糕的做法。诸如字体设置之类的事情应该在类构造函数中完成,而不是在每次绘制视图时都完成。

于 2011-03-06T21:07:40.287 回答
1

哦,我的错,它实际上确实改变了字体。

只是它没有出现在 Eclipse 的预览中,但它确实显示在模拟器上。

问题解决了。

于 2011-01-21T09:41:44.837 回答
0
public class CustomTextView extends TextView {

 public CustomTextView(Context context, AttributeSet attributes) {
  super(context, attributes);
  applyCustomFont(context);
 }

 private void applyCustomFont(Context context) {
  TypeFace customTypeFace = Typeface.createFromAsset(context.getAssets(), "custom_font_name");
  setTypeface(customTypeFace);
 }

 @Override
 public void setTextAppearance(Context context, int resid) {
  super.setTextAppearance(context, resid);
  applyCustomFont(context);
 }
}

代码片段创建了一个自定义TextView,并在创建 textview 期间设置了自定义字体。
当您尝试以编程方式设置文本外观时,自定义字体会被重置。因此,您可以覆盖该setTextAppearance方法并再次设置自定义字体。

于 2014-06-18T05:48:30.290 回答