您的位置:首页 >8.3.15 Paint API之——Typeface(字型)
发布于2026-08-12 阅读(0)
扫一扫,手机访问
这一节聊的是 Paint API 系列里的最后一个 API——Typeface(字型)。顾名思义,它主要就是拿来设置字体以及字体风格的,而且上手门槛并不高,用起来也很直接。接下来,就把 Typeface 的几种常见用法顺着梳理一遍。
官方API文档:Typeface~
四个整型常量:
- BOLD:加粗
- ITALIC:斜体
- BOLD_ITALIC:粗斜体
- NORMAL:正常
Android系统默认支持三种字体,分别为:sans,serif,monospace 而提供的可选静态对象值有五个:
- DEFAULT:默认正常字体对象
- DEFAULT_BOLD:默认的字体对象,注意:这实际上不可能是粗体的,这取决于字体设置。 由getStyle()来确定
- MONOSPACE:monospace 字体风格
- SANS_SERIF:sans serif字体风格
- SERIF:serif字体风格
如果系统默认提供的那三种字体不太合心意,比如更偏爱 MAC 上常见的Monaco字体,其实也可以把它用到自己的 APP 里。做法并不复杂:先把对应的 TTF 文件准备好,接着放进assets/font/目录,然后创建相应的对象就行。关键代码如下:
Typeface typeFace =Typeface.createFromAsset(getAssets(),"font/MONACO.ttf");
运行效果图:

自定义的View类:MyView.ja va:
/**
* Created by Jay on 2015/11/5 0005.
*/
public class MyView extends View{
private Paint mPaint1,mPaint2,mPaint3,mPaint4,mPaint5;
private Context mContext;
public MyView(Context context) {
this(context,null);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(){
mPaint1 = new Paint();
mPaint2 = new Paint();
mPaint3 = new Paint();
mPaint4 = new Paint();
mPaint5 = new Paint();
mPaint1.setColor(Color.RED);
mPaint2.setColor(Color.BLUE);
mPaint3.setColor(Color.BLACK);
mPaint4.setColor(Color.YELLOW);
mPaint5.setColor(Color.GRAY);
mPaint1.setTextSize(100);
mPaint2.setTextSize(100);
mPaint3.setTextSize(100);
mPaint4.setTextSize(100);
mPaint5.setTextSize(100);
mPaint1.setTypeface(Typeface.DEFAULT_BOLD);
mPaint2.setTypeface(Typeface.MONOSPACE);
mPaint3.setTypeface(Typeface.SANS_SERIF);
mPaint4.setTypeface(Typeface.SERIF);
mPaint5.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "font/MONACO.ttf"));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText("Coder-pig", 100, 100, mPaint1);
canvas.drawText("Coder-pig", 100, 200, mPaint2);
canvas.drawText("Coder-pig", 100, 300, mPaint3);
canvas.drawText("Coder-pig", 100, 400, mPaint4);
canvas.drawText("Coder-pig", 100, 500, mPaint5);
}
}
恩呢,非常简单~就不解释了,要字体的可以自己百度或者下载示例代码~
TypefaceDemo.zip
好的,一连十几节的Paint API详解就到这里了,应该已经涵盖大部分的可能会用到的API了, 不知道你都Get了没,这些都是为我们进阶部分的自定义控件做铺垫~嗯,就说这么多,谢谢~
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
4
5
6
7
8
9