Ink Brush API を使用すると、キャンバスに描画するためのブラシを作成してカスタマイズできます。
ブラシを作成する
ブラシを作成するには、Brush.createWithColorLong() などの名前付き引数を使用して Brush ファクトリ メソッドを使用します。このクラスでは、次のプロパティを設定できます。
family: ブラシのスタイル。テキストの書体やフォントに似ています。使用可能なBrushFamily値については、StockBrushesをご覧ください。color: ブラシの色。色はColorLongを使用して設定できます。size: ブラシで作成されたストロークの基本の太さ。epsilon: ストローク内の 2 つの点を区別する必要がある最小距離。ストロークのジオメトリの詳細レベルまたは忠実度を制御します。- 値を大きくすると、ストロークがより単純化され、メモリ使用量が減り、レンダリングが速くなりますが、拡大したときにギザギザの縁などのアーティファクトが目立つことがあります。
- 値を小さくすると、高品質のズームでより多くの詳細が保持されますが、メモリ使用量が増加します。
- 1 px 単位スケールでプロトタイピングを行う場合は、0.1 から始めることをおすすめします。さまざまな画面密度をサポートする本番環境アプリでは、密度非依存単位(dp など)を使用し、それに応じてイプシロンを調整します。
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
)