The Brush APIs provide you with the tools to
define the visual style of your strokes. You can create brushes with different
colors, sizes, and families to achieve a variety of looks.
Create a brush
To create a brush, use the Compose Brush
companion methods with named arguments such as
Brush.Companion.createWithComposeColor.
This class lets you set the following properties:
family: The style of the brush, analogous to a typeface or font in text. SeeStockBrushesfor availableBrushFamilyvalues.color: The color of the brush. You can set the color using aColorLong.size: The overall thickness of strokes created with the brush.epsilon: The smallest distance for which two points should be considered visually distinct for stroke generation geometry purposes. The ratio of epsilon and stroke points controls how much a stroke can be zoomed in on without artifacts, at the cost of memory. A good starting point for stroke units is 1 px, and a good starting point for epsilon is 0.1. Higher epsilon values use less memory but allow for less zoom before triangle artifacts appear. Experiment to find the right value for your use case.
val brush = Brush.createWithComposeColor(
family = StockBrushes.pressure(),
colorIntArgb = Color.Black,
size = 5F,
epsilon = 0.1F
)
Modify brush properties
You can create a copy of an existing brush using the
copyWithComposeColor() method, which lets you
change any of the brush's properties.
val redBrush = Brush.createWithComposeColor(
family = StockBrushes.pressurePen(),
colorIntArgb = Color.RED,
size = 5F,
epsilon = 0.1F
)
val blueBrush = redBrush.copyWithComposeColor(color = Color.BLUE)
Custom Brushes
虽然 StockBrushes 提供了一组通用的多功能笔刷,但 Ink API 还提供了一种高级方法,用于创建全新的笔刷行为,以实现独特的艺术效果,或复制特定的现有笔刷以实现向后兼容性。
自定义 BrushFamily 从其序列化格式加载。所需格式为 BrushFamily 协议缓冲区的 gzip 压缩二进制编码。这样一来,您就可以立即加载和使用自定义笔刷文件。反序列化后,自定义 BrushFamily 可用于创建具有特定颜色和大小的新 Brush,就像任何 StockBrushes 系列一样。
class CustomBrushes(val context: Context) {
private const val TAG = "CustomBrushes"
val brushes by lazy { loadCustomBrushes(context) }
@OptIn(ExperimentalInkCustomBrushApi::class)
private fun loadCustomBrushes(): List<CustomBrush> {
val brushFiles = mapOf(
"Calligraphy" to (R.raw.calligraphy to R.drawable.draw_24px),
"Flag Banner" to (R.raw.flag_banner to R.drawable.flag_24px),
"Graffiti" to (R.raw.graffiti to R.drawable.format_paint_24px),
// ...
)
val loadedBrushes = brushFiles.mapNotNull { (name, pair) ->
val (resourceId, icon) = pair
val brushFamily = context.resources.openRawResource(resourceId).use
{ inputStream ->
BrushFamily.decode(inputStream)
}
CustomBrush(name, icon, brushFamily.copy(clientBrushFamilyId = name))
}
return loadedBrushes
}
}
data class CustomBrush(
val name: String,
val icon: Int,
val brushFamily: BrushFamily
)