0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Compose で矢印つきの吹き出し

0
Posted at

はじめに

アプリを初めて開いたときに、「このボタンで保存できます」のように、画面の部品を矢印で指しながら説明する吹き出しを Jetpack Compose で作りました。

help_balloon.png

ライブラリは使わずに作っています。少し長くなるので、前編・後編の 2 回に分けて紹介します。

  • 前編(この記事):指したい部品の位置を記録して、吹き出しをその下(入らなければ上)に表示する
  • 後編:部品を指す矢印を描く/スクロールで隠れている部品を指す

① 指したい部品の位置を記録する

部品ごとに id を付けて、画面のどこにあるかを記録します。

class HelpTargets {
    private val bounds = mutableStateMapOf<String, Rect>()

    fun boundsOf(id: String): Rect? = bounds[id]
    fun update(id: String, rect: Rect) { bounds[id] = rect }
}

fun Modifier.helpTarget(targets: HelpTargets, id: String): Modifier =
    onGloballyPositioned { targets.update(id, it.boundsInRoot()) }

指したい部品に Modifier を付けるだけで、位置が記録されます。

Button(onClick = { /* ... */ }, modifier = Modifier.helpTarget(targets, "save")) {
    Text("保存")
}
  • onGloballyPositioned は、部品が画面に並んだときや動いたときに呼ばれます
  • boundsInRoot() で、画面全体の中での位置(四角形)が取れます
  • mutableStateMapOf に入れているので、部品が動くと吹き出しも付いてきます

② 吹き出しを下か上に表示する

吹き出しは、画面全体に重ねた Box の中に置きます。

@Composable
fun HelpOverlay(targetId: String, message: String, targets: HelpTargets) {
    var origin by remember { mutableStateOf(Offset.Zero) }
    Box(Modifier.fillMaxSize().onGloballyPositioned { origin = it.boundsInRoot().topLeft }) {
        // 記録した位置は画面全体が基準なので、この Box が基準になるようにずらす
        val target = targets.boundsOf(targetId)?.translate(-origin) ?: return@Box
        HelpBalloon(message, target)
    }
}

記録した位置は画面全体が基準です。重ねる Box が画面の一番上からずれていると、吹き出しの位置もずれるので、Box 自身の位置を引いてそろえています。

次に、吹き出しを部品の下に出すか、上に出すかを決めます。

@Composable
fun HelpBalloon(message: String, target: Rect) {
    BoxWithConstraints(Modifier.fillMaxSize()) {
        val density = LocalDensity.current
        val screenWidth = constraints.maxWidth.toFloat()
        val screenHeight = constraints.maxHeight.toFloat()
        val width = with(density) { 280.dp.toPx() }
        val spacing = with(density) { 16.dp.toPx() }

        // 吹き出しの高さは、一度並べてみないと分からない
        var height by remember { mutableStateOf<Int?>(null) }
        val h = (height ?: 0).toFloat()

        // 下に入るなら下、入らなければ上
        val below = screenHeight - target.bottom >= h + spacing
        val y = if (below) target.bottom + spacing else target.top - h - spacing
        // 部品の真ん中に合わせつつ、画面からはみ出さないようにする
        val x = (target.center.x - width / 2).coerceIn(spacing, screenWidth - width - spacing)

        Text(
            text = message,
            modifier = Modifier
                .offset { IntOffset(x.roundToInt(), y.roundToInt()) }
                .width(with(density) { width.toDp() })
                .alpha(if (height == null) 0f else 1f) // 高さが分かるまでは見せない
                .onSizeChanged { height = it.height }
                .background(Color.White, RoundedCornerShape(12.dp))
                .padding(16.dp),
        )
    }
}

吹き出しの高さは文章の長さで変わるので、一度並べて onSizeChanged で高さを測ってから位置を決めています。
測る前は位置が正しくないので、alpha で見えないようにしておくと、一瞬変な位置に出るのを防げます。

help_balloon_part1.png

補足

  • 重ねる Box はタッチを受け取らないので、吹き出しを出したまま下の画面をスクロールできます。吹き出し自体へのタップを下に通したくない場合は、吹き出しに .pointerInput(Unit) { detectTapGestures {} } を付けます
  • 画像では、説明中に半透明の黒い Box を画面全体に重ねて、背景を暗くしています

まとめ

  • 部品の位置は onGloballyPositioned と boundsInRoot() で記録し、重ねる Box の位置を引いてそろえる
  • 吹き出しは一度並べて高さを測ってから、下に入るか上に出すかを決める

後編では、吹き出しに部品を指す矢印を付けて完成させます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?