Brush API を使用すると、ストロークのビジュアル スタイルを定義するツールを利用できます。さまざまな色、サイズ、ファミリーのブラシを作成して、さまざまなルックを実現できます。
ブラシを作成する
ブラシを作成するには、Compose の Brush コンパニオン メソッドを Brush.Companion.createWithComposeColor などの名前付き引数とともに使用します。このクラスでは、次のプロパティを設定できます。
family: ブラシのスタイル。テキストの書体やフォントに似ています。使用可能なBrushFamily値については、StockBrushesをご覧ください。color: ブラシの色。色はColorLongを使用して設定できます。size: ブラシで作成されたストロークの全体的な太さ。epsilon: ストローク生成ジオメトリの目的で、2 つのポイントが視覚的に区別されると見なされる最小距離。イプシロンとストローク ポイントの比率は、メモリを消費する代わりに、アーティファクトなしでストロークを拡大できる量を制御します。ストローク単位の適切な開始点は 1 ピクセル、イプシロンの適切な開始点は 0.1 です。イプシロン値が大きいほど、使用するメモリは少なくなりますが、三角形のアーティファクトが表示される前にズームできる範囲が狭くなります。ユースケースに適した値を見つけるためにテストします。
val brush = Brush.createWithComposeColor(
family = StockBrushes.pressure(),
colorIntArgb = Color.Black,
size = 5F,
epsilon = 0.1F
)
ブラシのプロパティを変更する
copyWithComposeColor() メソッドを使用すると、既存のブラシのコピーを作成して、ブラシのプロパティを変更できます。
val redBrush = Brush.createWithComposeColor(
family = StockBrushes.pressurePen(),
colorIntArgb = Color.RED,
size = 5F,
epsilon = 0.1F
)
val blueBrush = redBrush.copyWithComposeColor(color = Color.BLUE)
カスタムブラシ
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
)