当前位置: 首页 > 工具软件 > Calligraphy > 使用案例 >

android 字体编程,Android编程之Calligraphy:Android 自定义字体库

皮景龙
2023-12-01

Calligraphy是android 自定义字体库

添加依赖

Download from Maven Central (.jar)

OR

Java

dependencies {

compile 'uk.co.chrisjenx:calligraphy:1.2.0'

}

123

dependencies {    compile 'uk.co.chrisjenx:calligraphy:1.2.0'}

使用

字体

把你的所有的自定义字体都添加到assets/fonts 目录下, 所有的字体引用的都是这个目录

自定义属性

我们没有在Jar包中打包  R.attr,所以你需要自己添加你自己的Attr,下面是一个例子  res/values/attrs.xml

Java

1234

配置

在Application类中,使用 CalligraphyConfig定义你默认的字体, 不幸的是Activity#onCreate(Bundle) 在 Activity#attachBaseContext(Context)之后调用, 所以这个配置文件要在之前定义

Java

protected void onCreate() {

super.onCreate();

CalligraphyConfig.initDefault("fonts/Roboto-Regular.ttf", R.attr.fontPath);

//....

}

12345

protected void onCreate() {    super.onCreate();    CalligraphyConfig.initDefault("fonts/Roboto-Regular.ttf", R.attr.fontPath);    //....}

注入到 Context

Java

@Override

protected void attachBaseContext(Context newBase) {

super.attachBaseContext(new CalligraphyContextWrapper(newBase));

}

1234

@Overrideprotected void attachBaseContext(Context newBase) {    super.attachBaseContext(new CalligraphyContextWrapper(newBase));}

给TextView自定义字体

Java

android:text="@string/hello_world"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

fontPath="fonts/Roboto-Bold.ttf"/>

12345

在TextAppearance中自定义字体

Java

fonts/RobotoCondensed-Regular.ttf

android:text="@string/hello_world"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="@style/TextAppearance.FontPath"/>

123456789

在styles中自定义字体

Java

fonts/RobotoCondensed-Regular.ttf

123

Custom font defined in Theme

Java

@style/AppTheme.Widget.TextView

fonts/Roboto-ThinItalic.ttf

  

开源地址:https://github.com/chrisjenx/Calligraphy

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!

 类似资料: