summaryrefslogtreecommitdiff
path: root/android-app/app/src/main/kotlin/org/terst/nav/BarometerTrendView.kt
blob: 944d198d1746b67490fcfb3717b11e093ca43640 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package org.terst.nav

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat

class BarometerTrendView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private var history: List<BarometerReading> = emptyList()

    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = ContextCompat.getColor(context, R.color.instrument_text_normal)
        strokeWidth = 4f
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
    }

    private val gridPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = ContextCompat.getColor(context, R.color.instrument_text_secondary)
        strokeWidth = 1f
        style = Paint.Style.STROKE
    }

    fun setHistory(newHistory: List<BarometerReading>) {
        history = newHistory
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (history.size < 2) return

        val padding = 20f
        val w = width.toFloat() - 2 * padding
        val h = height.toFloat() - 2 * padding

        val minP = history.minOf { it.pressureHpa }
        val maxP = history.maxOf { it.pressureHpa }
        val rangeP = (maxP - minP).coerceAtLeast(1.0f) // Show at least 1 hPa range

        val minT = history.first().timestamp
        val maxT = history.last().timestamp
        val rangeT = (maxT - minT).coerceAtLeast(1L)

        // Draw simple grid
        canvas.drawLine(padding, padding, padding, h + padding, gridPaint)
        canvas.drawLine(padding, h + padding, w + padding, h + padding, gridPaint)

        val path = Path()
        history.forEachIndexed { index, reading ->
            val x = padding + (reading.timestamp - minT).toFloat() / rangeT * w
            val y = padding + h - (reading.pressureHpa - minP) / rangeP * h

            if (index == 0) {
                path.moveTo(x, y)
            } else {
                path.lineTo(x, y)
            }
        }

        canvas.drawPath(path, linePaint)
    }
}