0
# Font Resources
1
2
Font resources provide type-safe access to custom fonts with support for variable fonts, multiple weights, styles, and font variation settings. The library handles font loading across all Compose Multiplatform targets with platform-specific optimizations.
3
4
## Core Types
5
6
```kotlin { .api }
7
class FontResource(id: String, items: Set<ResourceItem>) : Resource(id, items)
8
```
9
10
A font resource represents a font file (TTF, OTF, or variable font) that can be loaded and used in text rendering.
11
12
## Composable Functions
13
14
### Font Creation
15
16
```kotlin { .api }
17
@Composable
18
expect fun Font(
19
resource: FontResource,
20
weight: FontWeight = FontWeight.Normal,
21
style: FontStyle = FontStyle.Normal,
22
variationSettings: FontVariation.Settings = FontVariation.Settings(weight, style)
23
): Font
24
```
25
26
Creates a Font object from a font resource with specified weight, style, and variation settings. This is a platform-specific expect function with different implementations for each target.
27
28
**Parameters:**
29
- `resource` - The font resource to load
30
- `weight` - Font weight (Thin, Light, Normal, Medium, Bold, etc.)
31
- `style` - Font style (Normal, Italic)
32
- `variationSettings` - Custom font variation settings for variable fonts
33
34
**Usage:**
35
```kotlin
36
@Composable
37
fun CustomText() {
38
val regularFont = Font(
39
resource = Res.font.custom_font,
40
weight = FontWeight.Normal,
41
style = FontStyle.Normal
42
)
43
44
val boldFont = Font(
45
resource = Res.font.custom_font,
46
weight = FontWeight.Bold,
47
style = FontStyle.Normal
48
)
49
50
val fontFamily = FontFamily(regularFont, boldFont)
51
52
Text(
53
text = "Custom Typography",
54
fontFamily = fontFamily,
55
fontWeight = FontWeight.Bold
56
)
57
}
58
```
59
60
### Variable Font Support
61
62
```kotlin
63
@Composable
64
fun VariableFontExample() {
65
val variableFont = Font(
66
resource = Res.font.variable_font,
67
weight = FontWeight.Medium,
68
style = FontStyle.Normal,
69
variationSettings = FontVariation.Settings(
70
FontVariation.weight(500),
71
FontVariation.slant(-15f),
72
FontVariation.width(75f)
73
)
74
)
75
76
Text(
77
text = "Variable Font Text",
78
fontFamily = FontFamily(variableFont)
79
)
80
}
81
```
82
83
## Suspend Functions
84
85
### Raw Font Bytes
86
87
```kotlin { .api }
88
suspend fun getFontResourceBytes(
89
environment: ResourceEnvironment,
90
resource: FontResource
91
): ByteArray
92
```
93
94
Retrieves the raw byte content of a font resource. Useful for custom font processing or integration with platform-specific font APIs.
95
96
**Parameters:**
97
- `environment` - Resource environment for variant selection
98
- `resource` - The font resource to load
99
100
**Usage:**
101
```kotlin
102
suspend fun installSystemFont(fontResource: FontResource) {
103
val environment = getSystemResourceEnvironment()
104
val fontBytes = getFontResourceBytes(environment, fontResource)
105
106
// Install font at system level (platform-specific)
107
systemFontManager.installFont(fontBytes)
108
}
109
110
suspend fun analyzeFontMetrics(fontResource: FontResource): FontMetrics {
111
val environment = getSystemResourceEnvironment()
112
val fontBytes = getFontResourceBytes(environment, fontResource)
113
114
return FontAnalyzer.analyze(fontBytes)
115
}
116
```
117
118
## Font Weights and Styles
119
120
### Standard Font Weights
121
122
```kotlin { .api }
123
// Available FontWeight values
124
FontWeight.Thin // 100
125
FontWeight.ExtraLight // 200
126
FontWeight.Light // 300
127
FontWeight.Normal // 400 (default)
128
FontWeight.Medium // 500
129
FontWeight.SemiBold // 600
130
FontWeight.Bold // 700
131
FontWeight.ExtraBold // 800
132
FontWeight.Black // 900
133
134
// Custom weights
135
FontWeight(350) // Custom weight value
136
```
137
138
### Font Styles
139
140
```kotlin { .api }
141
FontStyle.Normal // Upright text
142
FontStyle.Italic // Slanted text
143
```
144
145
**Usage Examples:**
146
```kotlin
147
@Composable
148
fun FontStyleExamples() {
149
val fontFamily = FontFamily(
150
Font(Res.font.my_font, FontWeight.Light, FontStyle.Normal),
151
Font(Res.font.my_font, FontWeight.Normal, FontStyle.Normal),
152
Font(Res.font.my_font, FontWeight.Bold, FontStyle.Normal),
153
Font(Res.font.my_font, FontWeight.Normal, FontStyle.Italic)
154
)
155
156
Column {
157
Text("Light", fontFamily = fontFamily, fontWeight = FontWeight.Light)
158
Text("Normal", fontFamily = fontFamily, fontWeight = FontWeight.Normal)
159
Text("Bold", fontFamily = fontFamily, fontWeight = FontWeight.Bold)
160
Text("Italic", fontFamily = fontFamily, fontStyle = FontStyle.Italic)
161
}
162
}
163
```
164
165
## Variable Font Features
166
167
### Font Variation Axes
168
169
Variable fonts support various axes for customization:
170
171
```kotlin { .api }
172
FontVariation.weight(value: Int) // Weight axis (wght)
173
FontVariation.width(value: Float) // Width axis (wdth)
174
FontVariation.slant(value: Float) // Slant axis (slnt)
175
FontVariation.italic(value: Float) // Italic axis (ital)
176
177
// Custom variation settings
178
FontVariation.Settings(
179
FontVariation.Setting("GRAD", 150f), // Custom axis
180
FontVariation.weight(600),
181
FontVariation.width(90f)
182
)
183
```
184
185
**Advanced Variable Font Usage:**
186
```kotlin
187
@Composable
188
fun AdvancedVariableFont() {
189
val customSettings = FontVariation.Settings(
190
FontVariation.weight(450), // Semi-medium weight
191
FontVariation.width(85f), // Condensed width
192
FontVariation.slant(-8f), // Slight slant
193
FontVariation.Setting("GRAD", 100f) // Grade axis
194
)
195
196
val font = Font(
197
resource = Res.font.variable_font,
198
variationSettings = customSettings
199
)
200
201
Text(
202
text = "Advanced Typography",
203
fontFamily = FontFamily(font)
204
)
205
}
206
```
207
208
## Font Family Management
209
210
### Creating Font Families
211
212
```kotlin
213
@Composable
214
fun CompleteFontFamily() {
215
val fontFamily = FontFamily(
216
// Regular variants
217
Font(Res.font.my_font_regular, FontWeight.Normal, FontStyle.Normal),
218
Font(Res.font.my_font_italic, FontWeight.Normal, FontStyle.Italic),
219
220
// Bold variants
221
Font(Res.font.my_font_bold, FontWeight.Bold, FontStyle.Normal),
222
Font(Res.font.my_font_bold_italic, FontWeight.Bold, FontStyle.Italic),
223
224
// Light variants
225
Font(Res.font.my_font_light, FontWeight.Light, FontStyle.Normal),
226
Font(Res.font.my_font_light_italic, FontWeight.Light, FontStyle.Italic)
227
)
228
229
MaterialTheme(
230
typography = Typography(
231
h1 = TextStyle(fontFamily = fontFamily, fontWeight = FontWeight.Bold),
232
body1 = TextStyle(fontFamily = fontFamily, fontWeight = FontWeight.Normal),
233
caption = TextStyle(fontFamily = fontFamily, fontWeight = FontWeight.Light)
234
)
235
) {
236
// App content with custom typography
237
AppContent()
238
}
239
}
240
```
241
242
## Supported Font Formats
243
244
### TrueType Fonts (TTF)
245
- Wide compatibility across all platforms
246
- Standard format for most fonts
247
- Good performance and rendering quality
248
249
### OpenType Fonts (OTF)
250
- Advanced typography features
251
- Better support for complex scripts
252
- Enhanced glyph rendering
253
254
### Variable Fonts
255
- Single file contains multiple style variations
256
- Efficient for reducing bundle size
257
- Advanced customization through variation axes
258
259
**File Extensions:**
260
- `.ttf` - TrueType Font
261
- `.otf` - OpenType Font
262
- `.ttc` - TrueType Collection
263
- Variable fonts use same extensions with internal variation data
264
265
## Platform-Specific Behavior
266
267
### Android
268
- Native font rendering with hardware acceleration
269
- Support for all standard font formats
270
- Automatic font fallback for missing glyphs
271
272
### Desktop (JVM)
273
- Skia-based font rendering for consistency
274
- Cross-platform font metrics and appearance
275
- Support for system font fallbacks
276
277
### iOS
278
- Core Text integration for optimal performance
279
- Native font rendering with Apple's font stack
280
- Excellent text rendering quality
281
282
### Web (JS/Wasm)
283
- Browser-based font rendering
284
- Web font loading with proper fallbacks
285
- Canvas text rendering for complex layouts
286
287
## Performance Considerations
288
289
### Font Loading
290
291
**Best Practices:**
292
1. **Preload frequently used fonts** in app initialization
293
2. **Use font families efficiently** - avoid loading unused weights/styles
294
3. **Consider variable fonts** for multiple style variations
295
4. **Cache font objects** when possible
296
297
**Font Loading Example:**
298
```kotlin
299
@Composable
300
fun OptimizedFontLoading() {
301
// Load fonts once and reuse
302
val fontFamily = remember {
303
FontFamily(
304
Font(Res.font.primary_regular, FontWeight.Normal),
305
Font(Res.font.primary_bold, FontWeight.Bold)
306
)
307
}
308
309
// Use throughout the composition
310
CompositionLocalProvider(LocalTextStyle provides TextStyle(fontFamily = fontFamily)) {
311
AppContent()
312
}
313
}
314
```
315
316
### Memory Management
317
318
- Font objects are cached automatically
319
- Unused fonts are eligible for garbage collection
320
- Variable fonts are more memory-efficient than multiple static fonts
321
322
## Error Handling
323
324
**Common Exceptions:**
325
- `MissingResourceException` - Font file not found
326
- `IllegalArgumentException` - Invalid font resource
327
- Platform-specific font loading errors
328
329
**Example Error Handling:**
330
```kotlin
331
@Composable
332
fun SafeFontLoading() {
333
val fontFamily = try {
334
FontFamily(Font(resource = Res.font.custom_font))
335
} catch (e: MissingResourceException) {
336
// Fallback to system font
337
FontFamily.Default
338
}
339
340
Text(
341
text = "Safe Font Text",
342
fontFamily = fontFamily
343
)
344
}
345
```
346
347
## Best Practices
348
349
1. **Organize fonts by family**:
350
```
351
font/
352
├── roboto_regular.ttf
353
├── roboto_bold.ttf
354
├── roboto_italic.ttf
355
└── roboto_bold_italic.ttf
356
```
357
358
2. **Use descriptive naming**:
359
```kotlin
360
Font(Res.font.headline_bold) // Good
361
Font(Res.font.font1) // Bad
362
```
363
364
3. **Consider font licensing**:
365
- Ensure fonts are properly licensed for distribution
366
- Check license compatibility with your app's license
367
368
4. **Test across platforms**:
369
- Font rendering can vary between platforms
370
- Test with actual content and different languages
371
372
5. **Optimize font selection**:
373
```kotlin
374
// Load only needed weights and styles
375
FontFamily(
376
Font(Res.font.app_font, FontWeight.Normal), // Most common
377
Font(Res.font.app_font, FontWeight.Bold) // For emphasis
378
// Skip unused weights like ExtraLight, Black, etc.
379
)
380
```
381
382
6. **Use variable fonts when appropriate**:
383
- Single file for multiple variations
384
- Smooth transitions between weights/styles
385
- Better performance for complex typography needs