使用自定义字体的自定义文本视图
我正在尝试实现一个使用我自己的自定义字体的自定义文本视图。
有没有办法在执行 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()来这样做?
I'm trying to implement a custom textview that uses my own custom font.
is there a way to set the typeface before doing a Super.onDraw()?
So as to replace the usual font to the custom font that I want to use.
Something like:
protected void onDraw(Canvas canvas)
{
Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfonts.ttf");
this.setTypeface(font1);
this.setTextSize(18);
super.onDraw(canvas);
}
I know the above code won't work.
Or do I have no choice but to use drawText() to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哦,我的糟糕,它确实改变了字体。
只是它没有显示在 Eclipse 的预览中,但它确实显示在模拟器上。
问题解决了。
Oh my bad, it actually does change the font.
Just that it didn't show up on the preview on Eclipse but it does show on the emulator.
Problem solved.
该代码片段创建一个自定义
TextView
,并在创建文本视图期间设置自定义字体。当您尝试以编程方式设置文本外观时,自定义字体将被重置。因此,您可以重写 setTextAppearance 方法并再次设置自定义字体。
The code snippet creates a custom
TextView
and during the creation of the textview it set the custom font.When you try to programmatically set the text appearance, the custom font is reset. Hence you can override the
setTextAppearance
method and set the custom font again.每次调用 onDraw 方法时都创建新的 Typeface 对象是非常糟糕的做法。诸如字体设置之类的事情应该在类构造函数中完成,而不是在每次绘制视图时完成。
It's a very bad practice to create new Typeface object on every time when your onDraw method is called. Such things as font set up should be done in the class constructor but not on every time your view is being drawn.