失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Android 字体设置 Typeface 设置

Android 字体设置 Typeface 设置

时间:2023-06-22 10:11:37

相关推荐

Android  字体设置 Typeface 设置

今天在学习自定义View当中遇到了一个Typeface属性,所以遇见问题,就学习一下。

Android 自带字体有四种属性:“sans”, “serif”, “monospace","normal"

第一种通过xml属性去设置:

android:typeface="monospace" //sans,serif,normal

第二种通过java代码去设置:

①第一种构造方法

view.setTypeface(typeface,typefaceStyle);

属性不明白看源码:

/*** Sets the typeface and style in which the text should be displayed,* and turns on the fake bold and italic bits in the Paint if the* Typeface that you provided does not have all the bits in the* style that you specified.** @attr ref android.R.styleable#TextView_typeface* @attr ref android.R.styleable#TextView_textStyle*/public void setTypeface(Typeface tf, int style) {if (style > 0) {if (tf == null) {tf = Typeface.defaultFromStyle(style);} else {tf = Typeface.create(tf, style);}setTypeface(tf);// now compute what (if any) algorithmic styling is neededint typefaceStyle = tf != null ? tf.getStyle() : 0;int need = style & ~typefaceStyle;mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);} else {mTextPaint.setFakeBoldText(false);mTextPaint.setTextSkewX(0);setTypeface(tf);}}

两个参数含义:

typeface,就是一个Typeface 对象。 可以传空对象,若空对象就是走默认style

style,Typeface.NORMAL int值。

②另一个构造方法:

可以设置自定义的字体,对于在Android中引入其他字体,

要将字体文件保存在assets/fonts/目录下,字体文件有*.ttf和*.otf等格式

view.setTypeface(typeface);

Typeface typeface;

typeface = Typeface.createFromAsset(getAssets(), "fonts/regular.otf");//可以从assets中放入我们的自定义字体属性。

view.setTypeface(typeface);

看源码:

/*** Sets the typeface and style in which the text should be displayed.* Note that not all Typeface families actually have bold and italic* variants, so you may need to use* {@link #setTypeface(Typeface, int)} to get the appearance* that you actually want.** @see #getTypeface()** @attr ref android.R.styleable#TextView_fontFamily* @attr ref android.R.styleable#TextView_typeface* @attr ref android.R.styleable#TextView_textStyle*/public void setTypeface(Typeface tf) {if (mTextPaint.getTypeface() != tf) {mTextPaint.setTypeface(tf);//给绘制TextView的画笔,设置字体属性if (mLayout != null) {//如果布局不为空nullLayouts();requestLayout();//刷新layoutinvalidate();//刷新View控件}}}

关于自定义的Android字体,在加载的过程中由于文件的大小可能会影响App性能,

可以把加载字体放在App启动时候去加载,把Typeface设成static,使用的时候直接调用即可。

关于fount文件里的字体,我们只需要添加我们用到的字体,防止文件太大,加载过慢。

如果觉得《Android 字体设置 Typeface 设置》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。