墨水 Brush API 提供了一种创建和自定义画笔以在画布上绘制内容的方法。
创建画笔
如需创建画笔,请使用 Brush 工厂方法和命名实参(例如 Brush.createWithColorLong())。此类可让您设置以下属性:
family:笔刷的样式,类似于文本中的字体。 如需了解可用的BrushFamily值,请参阅StockBrushes。color:画笔的颜色。您可以使用ColorLong设置颜色。size:使用画笔创建的笔画的基本粗细。epsilon:笔画中两个点必须被视为不同的最小距离,用于控制笔画几何图形的细节或保真度。- 值越高,笔画越简化,使用的内存越少,渲染速度越快,但放大时可能会出现明显的伪影,例如锯齿状边缘。
- 值越低,在高画质缩放时保留的细节越多,但内存用量也会增加。
- 对于以 1 px 为单位比例进行的原型设计,0.1 是一个不错的起点。 对于支持各种屏幕密度的正式版应用,请使用密度无关单位(例如 dp),并相应地调整 epsilon。
val redBrush = Brush.createWithColorLong(
family = StockBrushes.pressurePen(),
colorLong = Color.RED.pack(),
size = 5F,
epsilon = 0.1F
)
修改笔刷属性
您可以使用 copy() 方法创建现有画笔的副本。通过此方法,您可以更改画笔的任何属性。
val blueBrush = redBrush.copy(colorLong = Color.BLUE.pack())
自定义画笔
While StockBrushes provides a versatile set of
common brushes, Ink API also offers an advanced path for creating entirely new
brush behaviors for unique artistic effects or to replicate specific existing
brushes for backward compatibility.
A custom BrushFamily is loaded from its serialized format. The required format
is the gzipped binary encoding of the
BrushFamily protocol buffer. This lets you load and use
custom brush files today. Once deserialized, the custom BrushFamily can be
used to create a new Brush with a specific color and size, just like any of
the StockBrushes families.
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
)