LoginSignup
1
1

Jetpack Composeで相対位置での配置をしたい(ConstraintLayoutのbiasみたいなやつ)

Last updated at Posted at 2024-05-12

概要

中央に置きたいだけならAlignment.Centerで良いのだがConstraintLayoutでいうところのこの辺と同じ様に相対位置で要素を配置したいという課題について調べた際の備忘録です。

  • layout_constraintVertical_bias
  • layout_constraintHorizontal_bias

結論

BiasAlignmentを使えば良い。
縦横ともに0fが中央になり、-1f〜1fの範囲内で指定する。

@Composable
fun BiasAlignmentSample() {
  Box(
    modifier = Modifier.fillMaxSize(),
    contentAlignment = BiasAlignment(
      horizontalBias = -0.8f,
      verticalBias = 0.7f
    )
  ) {
    Text("Sample")
  }
}

@Preview(
  showBackground = true,
  showSystemUi = true
)
@Composable
fun BiasAlignmentSamplePreview() {
  BiasAlignmentSample()
}

上記のようなコードだとプロット位置はこうなる。

x軸は負の数を指定すると中央より左に、正の数を指定すると中央よりも右になる。
y軸は負の数を指定すると中央より上に、正の数を指定すると中央よりも下になる。

余談

0,0が中央になるなら数直線をイメージしてしまうけど、y軸方向が逆になって気持ち悪い:thinking:
(ConstraintLayoutのbiasと同じ挙動ですね)

今回の記事にまとめるにあたり、普段何気なく使っていたAlignmentの実装を見てみたら全てこいつで定義されていた。

@Stable
fun interface Alignment {
    fun align(size: IntSize, space: IntSize, layoutDirection: LayoutDirection): IntOffset


    @Stable
    fun interface Horizontal {
        fun align(size: Int, space: Int, layoutDirection: LayoutDirection): Int
    }

    @Stable
    fun interface Vertical {
        fun align(size: Int, space: Int): Int
    }

    companion object {
        // 2D Alignments.
        @Stable
        val TopStart: Alignment = BiasAlignment(-1f, -1f)
        @Stable
        val TopCenter: Alignment = BiasAlignment(0f, -1f)
        @Stable
        val TopEnd: Alignment = BiasAlignment(1f, -1f)
        @Stable
        val CenterStart: Alignment = BiasAlignment(-1f, 0f)
        @Stable
        val Center: Alignment = BiasAlignment(0f, 0f)
        @Stable
        val CenterEnd: Alignment = BiasAlignment(1f, 0f)
        @Stable
        val BottomStart: Alignment = BiasAlignment(-1f, 1f)
        @Stable
        val BottomCenter: Alignment = BiasAlignment(0f, 1f)
        @Stable
        val BottomEnd: Alignment = BiasAlignment(1f, 1f)

        // 1D Alignment.Verticals.
        @Stable
        val Top: Vertical = BiasAlignment.Vertical(-1f)
        @Stable
        val CenterVertically: Vertical = BiasAlignment.Vertical(0f)
        @Stable
        val Bottom: Vertical = BiasAlignment.Vertical(1f)

        // 1D Alignment.Horizontals.
        @Stable
        val Start: Horizontal = BiasAlignment.Horizontal(-1f)
        @Stable
        val CenterHorizontally: Horizontal = BiasAlignment.Horizontal(0f)
        @Stable
        val End: Horizontal = BiasAlignment.Horizontal(1f)
    }
}

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1