Flutter 加载图片和字体文件

13 min read

加载图片

Flutter 中使用 AssetImage 组件展示图片。Flutter 会根据当前设备的分辨率加载对应的图片,我们只需要按照特定的目录结构来放置图片,例如:

assets
├── images
    ├── wechat.png
    ├── 2.0x
        ├── wechat.png
    ├── 3.0x
        ├── wechat.png

使用时:

new Image.asset("assets/images/wechat.png")

// or
new Image(
  image: new AssetImage("assets/images/wechat.png"),
),

加载字体

下载字体并在 pubspec.yaml 中配置,这里的配置方式和前面有一点区别:

fonts:
  - family: Charmonman
    fonts:
      - asset: assets/fonts/Charmonman-Regular.ttf
      - asset: assets/fonts/Charmonman-Bold.ttf
        weight: 500

其中 weight 属性指定字体的粗细,对应 TextStylefontWeight 属性,会匹配对应的字体。同理还有 style 属性,对应的值为 italicnormal

使用时,通过 TextStyle 指定对应的字体即可:

new Text(
  "A red flair silhouetted the jagged edge of a wing.",
  style: new TextStyle(
    fontFamily: "Charmonman",
    fontSize: 17.0,
    fontWeight: FontWeight.w500,
  ),
)

使用字体图标

字体图标的使用和普通字体使用没太大区别,只是文本内容使用对应图标的 Unicode 码点即可:

new Text(
  "\u{e7d7}",
  style: new TextStyle(
    fontFamily: "Iconfont",
    fontSize: 36.0,
  ),
),