/
SmoothLineGraph.kt
360 lines (329 loc) · 13.6 KB
/
SmoothLineGraph.kt
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package dev.riggaroo.composeplaytime
import android.graphics.PointF
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.annotation.RequiresApi
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toIntRect
import androidx.compose.ui.unit.toSize
import kotlinx.coroutines.launch
import java.math.BigDecimal
import java.time.LocalDate
import kotlin.math.roundToInt
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@OptIn(ExperimentalTextApi::class)
@RequiresApi(Build.VERSION_CODES.O)
@Preview
@Composable
fun SmoothLineGraph() {
Box(
modifier = Modifier
.background(PurpleBackgroundColor)
.fillMaxSize()
) {
val animationProgress = remember { Animatable(0f) }
var highlightedWeek by remember { mutableStateOf<Int?>(null) }
val localView = LocalView.current
LaunchedEffect(highlightedWeek) {
if (highlightedWeek != null) {
localView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
}
LaunchedEffect(key1 = graphData, block = {
animationProgress.animateTo(1f, tween(3000))
})
val coroutineScope = rememberCoroutineScope()
val textMeasurer = rememberTextMeasurer()
val labelTextStyle = MaterialTheme.typography.labelSmall
Spacer(
modifier = Modifier
.padding(8.dp)
.aspectRatio(3 / 2f)
.fillMaxSize()
.align(Alignment.Center)
.pointerInput(Unit) {
detectTapGestures {
coroutineScope.launch {
animationProgress.snapTo(0f)
animationProgress.animateTo(1f, tween(3000))
}
}
}
.pointerInput(Unit) {
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
highlightedWeek =
(offset.x / (size.width / (graphData.size - 1))).roundToInt()
},
onDragEnd = { highlightedWeek = null },
onDragCancel = { highlightedWeek = null },
onDrag = { change, _ ->
highlightedWeek =
(change.position.x / (size.width / (graphData.size - 1))).roundToInt()
}
)
}
.drawWithCache {
val path = generateSmoothPath(graphData, size)
val filledPath = Path()
filledPath.addPath(path)
filledPath.relativeLineTo(0f, size.height)
filledPath.lineTo(0f, size.height)
filledPath.close()
onDrawBehind {
val barWidthPx = 1.dp.toPx()
drawRect(BarColor, style = Stroke(barWidthPx))
val verticalLines = 4
val verticalSize = size.width / (verticalLines + 1)
repeat(verticalLines) { i ->
val startX = verticalSize * (i + 1)
drawLine(
BarColor,
start = Offset(startX, 0f),
end = Offset(startX, size.height),
strokeWidth = barWidthPx
)
}
val horizontalLines = 3
val sectionSize = size.height / (horizontalLines + 1)
repeat(horizontalLines) { i ->
val startY = sectionSize * (i + 1)
drawLine(
BarColor,
start = Offset(0f, startY),
end = Offset(size.width, startY),
strokeWidth = barWidthPx
)
}
// draw line
clipRect(right = size.width * animationProgress.value) {
drawPath(path, Color.Green, style = Stroke(2.dp.toPx()))
drawPath(
filledPath,
brush = Brush.verticalGradient(
listOf(
Color.Green.copy(alpha = 0.4f),
Color.Transparent
)
),
style = Fill
)
}
// draw highlight if user is dragging
highlightedWeek?.let {
this.drawHighlight(it, graphData, textMeasurer, labelTextStyle)
}
}
})
}
}
fun generatePath(data: List<Balance>, size: Size): Path {
val path = Path()
val numberEntries = data.size - 1
val weekWidth = size.width / numberEntries
val max = data.maxBy { it.amount }
val min = data.minBy { it.amount } // will map to x= 0, y = height
val range = max.amount - min.amount
val heightPxPerAmount = size.height / range.toFloat()
data.forEachIndexed { i, balance ->
if (i == 0) {
path.moveTo(
0f,
size.height - (balance.amount - min.amount).toFloat() *
heightPxPerAmount
)
}
val balanceX = i * weekWidth
val balanceY = size.height - (balance.amount - min.amount).toFloat() *
heightPxPerAmount
path.lineTo(balanceX, balanceY)
}
return path
}
fun generateSmoothPath(data: List<Balance>, size: Size): Path {
val path = Path()
val numberEntries = data.size - 1
val weekWidth = size.width / numberEntries
val max = data.maxBy { it.amount }
val min = data.minBy { it.amount } // will map to x= 0, y = height
val range = max.amount - min.amount
val heightPxPerAmount = size.height / range.toFloat()
var previousBalanceX = 0f
var previousBalanceY = size.height
data.forEachIndexed { i, balance ->
if (i == 0) {
path.moveTo(
0f,
size.height - (balance.amount - min.amount).toFloat() *
heightPxPerAmount
)
}
val balanceX = i * weekWidth
val balanceY = size.height - (balance.amount - min.amount).toFloat() *
heightPxPerAmount
// to do smooth curve graph - we use cubicTo, uncomment section below for non-curve
val controlPoint1 = PointF((balanceX + previousBalanceX) / 2f, previousBalanceY)
val controlPoint2 = PointF((balanceX + previousBalanceX) / 2f, balanceY)
path.cubicTo(
controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y,
balanceX, balanceY
)
previousBalanceX = balanceX
previousBalanceY = balanceY
}
return path
}
@OptIn(ExperimentalTextApi::class)
fun DrawScope.drawHighlight(
highlightedWeek: Int,
graphData: List<Balance>,
textMeasurer: TextMeasurer,
labelTextStyle: TextStyle
) {
val amount = graphData[highlightedWeek].amount
val minAmount = graphData.minBy { it.amount }.amount
val range = graphData.maxBy { it.amount }.amount - minAmount
val percentageHeight = ((amount - minAmount).toFloat() / range.toFloat())
val pointY = size.height - (size.height * percentageHeight)
// draw vertical line on week
val x = highlightedWeek * (size.width / (graphData.size - 1))
drawLine(
HighlightColor,
start = Offset(x, 0f),
end = Offset(x, size.height),
strokeWidth = 2.dp.toPx(),
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f))
)
// draw hit circle on graph
drawCircle(
Color.Green,
radius = 4.dp.toPx(),
center = Offset(x, pointY)
)
// draw info box
val textLayoutResult = textMeasurer.measure("$amount", style = labelTextStyle)
val highlightContainerSize = (textLayoutResult.size).toIntRect().inflate(4.dp.roundToPx()).size
val boxTopLeft = ( x - (highlightContainerSize.width / 2f))
.coerceIn(0f, size.width - highlightContainerSize.width)
drawRoundRect(
Color.White,
topLeft = Offset(boxTopLeft, 0f),
size = highlightContainerSize.toSize(),
cornerRadius = CornerRadius(8.dp.toPx())
)
drawText(
textLayoutResult,
color = Color.Black,
topLeft = Offset(boxTopLeft + 4.dp.toPx(), 4.dp.toPx())
)
}
// date + balance
// list of date + balanc
@RequiresApi(Build.VERSION_CODES.O)
val graphData = listOf(
Balance(LocalDate.now(), BigDecimal(65631)),
Balance(LocalDate.now().plusWeeks(1), BigDecimal(65931)),
Balance(LocalDate.now().plusWeeks(2), BigDecimal(65851)),
Balance(LocalDate.now().plusWeeks(3), BigDecimal(65931)),
Balance(LocalDate.now().plusWeeks(4), BigDecimal(66484)),
Balance(LocalDate.now().plusWeeks(5), BigDecimal(67684)),
Balance(LocalDate.now().plusWeeks(6), BigDecimal(66684)),
Balance(LocalDate.now().plusWeeks(7), BigDecimal(66984)),
Balance(LocalDate.now().plusWeeks(8), BigDecimal(70600)),
Balance(LocalDate.now().plusWeeks(9), BigDecimal(71600)),
Balance(LocalDate.now().plusWeeks(10), BigDecimal(72600)),
Balance(LocalDate.now().plusWeeks(11), BigDecimal(72526)),
Balance(LocalDate.now().plusWeeks(12), BigDecimal(72976)),
Balance(LocalDate.now().plusWeeks(13), BigDecimal(73589)),
)
data class Balance(val date: LocalDate, val amount: BigDecimal)
val PurpleBackgroundColor = Color(0xff322049)
val BarColor = Color.White.copy(alpha = 0.3f)
val HighlightColor = Color.White.copy(alpha = 0.7f)
@Preview
@Composable
fun CoordinateSystem(){
Box(modifier = Modifier
.fillMaxSize()
.drawBehind {
val barWidthPx = 1.dp.toPx()
drawRect(Color.White)
val verticalLines = size.width / 80.dp.toPx()
val verticalSize = size.width / (verticalLines + 1)
repeat(verticalLines.roundToInt()) { i ->
val startX = verticalSize * (i + 1)
drawLine(
Color.Gray,
start = Offset(startX, 0f),
end = Offset(startX, size.height),
strokeWidth = barWidthPx
)
}
val horizontalLines = size.height / 80.dp.toPx()
val sectionSize = size.height / (horizontalLines + 1)
repeat(horizontalLines.roundToInt()) { i ->
val startY = sectionSize * (i + 1)
drawLine(
BarColor,
start = Offset(0f, startY),
end = Offset(size.width, startY),
strokeWidth = barWidthPx
)
}
})
}