This commit is contained in:
coco
2026-07-03 15:56:07 +08:00
commit caef23209c
5767 changed files with 1004268 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
*.iml
.idea
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/buildSrc/build
/captures
.externalNativeBuild
.cxx
local.properties
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
+96
View File
@@ -0,0 +1,96 @@
# Compose Charts
This is a library that Draws and animates charts using Android Jetpack Compose library.
## Implementation:
latest_release = ![Release](https://jitpack.io/v/tehras/charts.svg)
build.gradle (app)
```groovy
dependecies {
implementation "com.github.tehras:charts:$latest_release"
}
```
settings.gradle
```
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io'}
}
```
## How it looks:
<img src="/assets/pie_chart.gif" width="200"> <img src="/assets/bar_chart.gif" width="200"> <img src="/assets/line_chart.gif" width="200">
## How to use Pie Chart:
```kotlin
@Composable
fun MyChartParent() {
PieChart(
pieChartData = PieChartData(listOf(Slice(...), Slice(...),....)),
// Optional properties.
modifier = Modifier.fillMaxSize(),
animation = simpleChartAnimation(),
sliceDrawer = SimpleSliceDrawer()
)
}
```
## How to use Bar Chart:
```kotlin
@Composable
fun MyBarChartParent() {
fun BarChart(
barChartData = BarChartData(bars = listOf(Bar(label = "Bar Label", value = 100f, color = Color.Red)),
// Optional properties.
modifier = Modifier.fillMaxSize(),
animation = simpleChartAnimation(),
barDrawer = SimpleBarDrawer(),
xAxisDrawer = SimpleXAxisDrawer(),
yAxisDrawer = SimpleYAxisDrawer(),
labelDrawer = SimpleValueDrawer()
)
}
```
## How to use Line Chart:
```kotlin
@Composable
fun MyLineChartParent() {
LineChart(
linesChartData = listOf(LineChartData(points = listOf(LineChartData.Point(1f,"Label 1"), ...))),
// Optional properties.
modifier = Modifier.fillMaxSize(),
animation = simpleChartAnimation(),
pointDrawer = FilledCircularPointDrawer(),
lineDrawer = SolidLineDrawer(),
xAxisDrawer = SimpleXAxisDrawer(),
yAxisDrawer = SimpleYAxisDrawer(),
horizontalOffset = 5f,
labels = listOf("label 1" ...)
)
}
```
## License
Copyright 2020 Taras Koshkin.
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.
+1
View File
@@ -0,0 +1 @@
/build
+29
View File
@@ -0,0 +1,29 @@
plugins {
id("com.android.application")
kotlin("android")
}
apply(from = rootProject.file("gradle/configure-android.gradle"))
apply(from = rootProject.file("gradle/configure-compose.gradle"))
dependencies {
implementation(Kotlin.stdLib)
implementation(Android.appcompat)
implementation(Android.activityCompose)
implementation(Compose.core)
implementation(Compose.layout)
implementation(Compose.material)
implementation(Compose.materialIconsExt)
implementation(Compose.foundation)
implementation(Compose.runtime)
// Previews weren't working when using debugImplementation
implementation(Compose.tooling)
implementation(project(":lib:pie"))
implementation(project(":lib:bar"))
implementation(project(":lib:line"))
}
android {
namespace = "com.github.tehras.charts"
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Charts">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,16 @@
package com.github.tehras.charts
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import com.github.tehras.charts.ui.ChartsApp
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContent {
ChartsApp()
}
}
}
@@ -0,0 +1,9 @@
package com.github.tehras.charts.theme
import androidx.compose.ui.graphics.Color
val Red200 = Color(0xfff297a2)
val Red300 = Color(0xffea6d7e)
val Red700 = Color(0xffdd0d3c)
val Red800 = Color(0xffd00036)
val Red900 = Color(0xffc20029)
@@ -0,0 +1,11 @@
package com.github.tehras.charts.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(8.dp)
)
@@ -0,0 +1,10 @@
package com.github.tehras.charts.theme
import androidx.compose.ui.unit.dp
object Margins {
val horizontal = 12.dp
val horizontalLarge = 24.dp
val vertical = 8.dp
val verticalLarge = 16.dp
}
@@ -0,0 +1,39 @@
package com.github.tehras.charts.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val LightThemeColors = lightColors(
primary = Red700,
primaryVariant = Red900,
onPrimary = Color.White,
secondary = Red700,
secondaryVariant = Red900,
onSecondary = Color.White,
error = Red800
)
private val DarkThemeColors = darkColors(
primary = Red300,
primaryVariant = Red700,
onPrimary = Color.Black,
secondary = Red300,
onSecondary = Color.White,
error = Red200
)
@Composable
fun ChartsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
MaterialTheme(
colors = if (darkTheme) DarkThemeColors else LightThemeColors,
shapes = shapes,
content = content
)
}
@@ -0,0 +1,25 @@
package com.github.tehras.charts.ui
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
sealed class ChartScreen {
object SelectChart : ChartScreen()
object Pie : ChartScreen()
object Bar : ChartScreen()
object Line : ChartScreen()
}
object ChartScreenStatus {
var currentChart by mutableStateOf<ChartScreen>(ChartScreen.SelectChart)
private set
fun navigateTo(screen: ChartScreen) {
currentChart = screen
}
fun navigateHome() {
navigateTo(ChartScreen.SelectChart)
}
}
@@ -0,0 +1,32 @@
package com.github.tehras.charts.ui
import androidx.compose.animation.Crossfade
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import com.github.tehras.charts.theme.ChartsTheme
import com.github.tehras.charts.ui.bar.BarChartScreen
import com.github.tehras.charts.ui.line.LineChartScreen
import com.github.tehras.charts.ui.pie.PieChartScreen
import com.github.tehras.charts.ui.selector.SelectChartScreen
@Composable
fun ChartsApp() {
ChartsTheme {
AppContent()
}
}
@Composable
fun AppContent() {
Crossfade(ChartScreenStatus.currentChart) { screen ->
Surface(color = MaterialTheme.colors.background) {
when (screen) {
ChartScreen.SelectChart -> SelectChartScreen()
ChartScreen.Pie -> PieChartScreen()
ChartScreen.Bar -> BarChartScreen()
ChartScreen.Line -> LineChartScreen()
}
}
}
}
@@ -0,0 +1,105 @@
package com.github.tehras.charts.ui.bar
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.White
import com.github.tehras.charts.bar.BarChartData
import com.github.tehras.charts.bar.BarChartData.Bar
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.Inside
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.Outside
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.XAxis
class BarChartDataModel {
private var colors = mutableListOf(
Color(0XFFF44336),
Color(0XFFE91E63),
Color(0XFF9C27B0),
Color(0XFF673AB7),
Color(0XFF3F51B5),
Color(0XFF03A9F4),
Color(0XFF009688),
Color(0XFFCDDC39),
Color(0XFFFFC107),
Color(0XFFFF5722),
Color(0XFF795548),
Color(0XFF9E9E9E),
Color(0XFF607D8B)
)
var labelDrawer: SimpleValueDrawer by mutableStateOf(SimpleValueDrawer(drawLocation = Inside))
private set
var barChartData by mutableStateOf(
BarChartData(
bars = listOf(
Bar(
label = "Bar1",
value = randomValue(),
color = randomColor()
),
Bar(
label = "Bar2",
value = randomValue(),
color = randomColor()
),
Bar(
label = "Bar3",
value = randomValue(),
color = randomColor()
)
)
)
)
val bars: List<Bar>
get() = barChartData.bars
var labelLocation: DrawLocation = Inside
set(value) {
val color = when (value) {
Inside -> White
Outside, XAxis -> Black
}
labelDrawer = SimpleValueDrawer(
drawLocation = value,
labelTextColor = color
)
field = value
}
fun addBar() {
barChartData = barChartData
.copy(bars = bars.toMutableList().apply {
add(
Bar(
label = "Bar${bars.size + 1}",
value = randomValue(),
color = randomColor()
)
)
})
}
fun removeBar() {
// Remove last.
barChartData = barChartData.copy(bars = bars.toMutableList().apply {
val lastBar = bars[bars.size - 1]
colors.add(lastBar.color)
remove(lastBar)
})
}
private fun randomValue(): Float = (100 * Math.random() + 25).toFloat()
private fun randomColor(): Color {
val randomIndex = (Math.random() * colors.size).toInt()
val color = colors[randomIndex]
colors.removeAt(randomIndex)
return color
}
}
@@ -0,0 +1,144 @@
package com.github.tehras.charts.ui.bar
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Remove
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.bar.BarChart
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation
import com.github.tehras.charts.theme.Margins
import com.github.tehras.charts.ui.ChartScreenStatus
@Composable
fun BarChartScreen() {
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = { ChartScreenStatus.navigateHome() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Go back to home")
}
},
title = { Text(text = "Bar Chart") }
)
},
) { BarChartScreenContent() }
}
@Composable
private fun BarChartScreenContent() {
val barChartDataModel = BarChartDataModel()
Column(
modifier = Modifier.padding(
horizontal = Margins.horizontal,
vertical = Margins.vertical
)
) {
BarChartRow(barChartDataModel)
DrawValueLocation(barChartDataModel) {
barChartDataModel.labelLocation = it
}
AddOrRemoveBar(barChartDataModel)
}
}
@Composable
fun DrawValueLocation(
barChartDataModel: BarChartDataModel,
newLocation: (DrawLocation) -> Unit
) {
val selectedAlignment = remember(barChartDataModel.labelDrawer) {
barChartDataModel.labelLocation
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = Margins.verticalLarge),
verticalAlignment = CenterVertically
) {
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = Margins.horizontal, vertical = Margins.vertical)
.align(CenterVertically)
) {
DrawLocation.values().forEach { location ->
OutlinedButton(
border = ButtonDefaults.outlinedBorder.takeIf { selectedAlignment == location },
onClick = { newLocation(location) }
) {
Text(location.name)
}
}
}
}
}
@Composable
fun AddOrRemoveBar(barChartDataModel: BarChartDataModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = Margins.vertical),
verticalAlignment = CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Button(
enabled = barChartDataModel.bars.size > 2,
onClick = { barChartDataModel.removeBar() },
shape = CircleShape
) { Icon(Icons.Filled.Remove, contentDescription = "Remove bar from chart") }
Row(
modifier = Modifier.padding(horizontal = Margins.horizontal),
verticalAlignment = CenterVertically
) {
Text(text = "Bars: ")
Text(
text = barChartDataModel.bars.count().toString(),
style = TextStyle(
fontWeight = FontWeight.ExtraBold,
fontSize = 18.sp
)
)
}
Button(
enabled = barChartDataModel.bars.size < 6,
onClick = { barChartDataModel.addBar() },
shape = CircleShape
) { Icon(Icons.Filled.Add, contentDescription = "Add bar to chart") }
}
}
@Composable
private fun BarChartRow(barChartDataModel: BarChartDataModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.padding(vertical = Margins.verticalLarge)
) {
BarChart(
barChartData = barChartDataModel.barChartData,
labelDrawer = barChartDataModel.labelDrawer
)
}
}
@Preview
@Composable
fun BarChartPreview() = BarChartScreen()
@@ -0,0 +1,65 @@
package com.github.tehras.charts.ui.line
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import com.github.tehras.charts.line.LineChartData
import com.github.tehras.charts.line.LineChartData.Point
import com.github.tehras.charts.line.renderer.line.SolidLineDrawer
import com.github.tehras.charts.line.renderer.point.FilledCircularPointDrawer
import com.github.tehras.charts.line.renderer.point.HollowCircularPointDrawer
import com.github.tehras.charts.line.renderer.point.NoPointDrawer
import com.github.tehras.charts.line.renderer.point.PointDrawer
import com.github.tehras.charts.ui.line.LineChartDataModel.PointDrawerType.Filled
import com.github.tehras.charts.ui.line.LineChartDataModel.PointDrawerType.Hollow
import com.github.tehras.charts.ui.line.LineChartDataModel.PointDrawerType.None
class LineChartDataModel {
var lineChartData by mutableStateOf(
LineChartData(
points = listOf(
Point(randomYValue(), "Label1"),
Point(randomYValue(), "Label2"),
Point(randomYValue(), "Label3"),
Point(randomYValue(), "Label4"),
Point(randomYValue(), "Label5"),
Point(randomYValue(), "Label6"),
Point(randomYValue(), "Label7")
),
lineDrawer = SolidLineDrawer(),
)
)
var lineChartData2 by mutableStateOf(
LineChartData(
points = listOf(
Point(randomYValue(), "Label1"),
Point(randomYValue(), "Label2"),
Point(randomYValue(), "Label3"),
),
lineDrawer = SolidLineDrawer(
color = Color(0xFF00FF00)
)
)
)
var horizontalOffset by mutableStateOf(5f)
var pointDrawerType by mutableStateOf(Filled)
val pointDrawer: PointDrawer
get() {
return when (pointDrawerType) {
None -> NoPointDrawer
Filled -> FilledCircularPointDrawer()
Hollow -> HollowCircularPointDrawer()
}
}
private fun randomYValue(): Float = (100f * Math.random()).toFloat() + 45f
enum class PointDrawerType {
None,
Filled,
Hollow
}
}
@@ -0,0 +1,125 @@
package com.github.tehras.charts.ui.line
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.github.tehras.charts.line.LineChart
import com.github.tehras.charts.theme.Margins.horizontal
import com.github.tehras.charts.theme.Margins.vertical
import com.github.tehras.charts.theme.Margins.verticalLarge
import com.github.tehras.charts.ui.ChartScreenStatus
import com.github.tehras.charts.ui.line.LineChartDataModel.PointDrawerType
@Composable
fun LineChartScreen() {
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = { ChartScreenStatus.navigateHome() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Go back to home")
}
},
title = { Text(text = "Line Chart") }
)
},
) { LineChartScreenContent() }
}
@Composable
fun LineChartScreenContent() {
val lineChartDataModel = LineChartDataModel()
Column(
modifier = Modifier.padding(
horizontal = horizontal,
vertical = vertical
)
) {
LineChartRow(lineChartDataModel)
HorizontalOffsetSelector(lineChartDataModel)
OffsetProgress(lineChartDataModel)
}
}
@Composable
fun HorizontalOffsetSelector(lineChartDataModel: LineChartDataModel) {
val selectedType = lineChartDataModel.pointDrawerType
Row(
modifier = Modifier.padding(
horizontal = horizontal,
vertical = verticalLarge
),
verticalAlignment = CenterVertically
) {
Text("Point Drawer")
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = horizontal, vertical = vertical)
.align(CenterVertically)
) {
PointDrawerType.values().forEach { type ->
OutlinedButton(
border = ButtonDefaults.outlinedBorder.takeIf { selectedType == type },
onClick = { lineChartDataModel.pointDrawerType = type }
) {
Text(type.name)
}
}
}
}
}
@Composable
fun OffsetProgress(lineChartDataModel: LineChartDataModel) {
Row(
modifier = Modifier.padding(horizontal = horizontal),
verticalAlignment = CenterVertically
) {
Text("Offset")
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.align(CenterVertically)
) {
Slider(
value = lineChartDataModel.horizontalOffset,
onValueChange = { lineChartDataModel.horizontalOffset = it },
valueRange = 0f.rangeTo(25f)
)
}
}
}
@Composable
fun LineChartRow(lineChartDataModel: LineChartDataModel) {
Box(
modifier = Modifier
.height(250.dp)
.fillMaxWidth()
) {
LineChart(
linesChartData = listOf(lineChartDataModel.lineChartData, lineChartDataModel.lineChartData2),
horizontalOffset = lineChartDataModel.horizontalOffset,
pointDrawer = lineChartDataModel.pointDrawer,
)
}
}
@Preview
@Composable
fun LineChartPreview() = LineChartScreen()
@@ -0,0 +1,77 @@
package com.github.tehras.charts.ui.pie
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import com.github.tehras.charts.piechart.PieChartData
class PieChartDataModel {
private var colors = mutableListOf(
Color(0XFFF44336),
Color(0XFFE91E63),
Color(0XFF9C27B0),
Color(0XFF673AB7),
Color(0XFF3F51B5),
Color(0XFF03A9F4),
Color(0XFF009688),
Color(0XFFCDDC39),
Color(0XFFFFC107),
Color(0XFFFF5722),
Color(0XFF795548),
Color(0XFF9E9E9E),
Color(0XFF607D8B)
)
var sliceThickness by mutableStateOf(25f)
var pieChartData by mutableStateOf(
PieChartData(
slices = listOf(
PieChartData.Slice(
randomLength(),
randomColor()
),
PieChartData.Slice(
randomLength(),
randomColor()
),
PieChartData.Slice(
randomLength(),
randomColor()
)
)
)
)
val slices
get() = pieChartData.slices
fun addSlice() {
pieChartData = pieChartData.copy(
slices = slices.toMutableList().apply {
add(PieChartData.Slice(randomLength(), randomColor()))
}.toList()
)
}
fun removeSlice() {
pieChartData = pieChartData.copy(
slices = slices.toMutableList().apply {
val lastSlice = slices[slices.size - 1]
colors.add(lastSlice.color)
remove(lastSlice)
}.toList()
)
}
private fun randomColor(): Color {
val randomIndex = (Math.random() * colors.size).toInt()
val color = colors[randomIndex]
colors.removeAt(randomIndex)
return color
}
private fun randomLength(): Float = (20 * Math.random() + 10).toFloat()
}
@@ -0,0 +1,149 @@
package com.github.tehras.charts.ui.pie
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Remove
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.piechart.PieChart
import com.github.tehras.charts.piechart.renderer.SimpleSliceDrawer
import com.github.tehras.charts.theme.Margins
import com.github.tehras.charts.ui.ChartScreenStatus
@Composable
fun PieChartScreen() {
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = { ChartScreenStatus.navigateHome() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Go back to home")
}
},
title = { Text(text = "Pie Chart") }
)
},
) { PieChartScreenContent() }
}
@Composable
private fun PieChartScreenContent() {
val pieChartDataModel = remember { PieChartDataModel() }
Column(
modifier = Modifier.padding(
horizontal = Margins.horizontal,
vertical = Margins.vertical
)
) {
PieChartRow(pieChartDataModel)
SliceThicknessRow(pieChartDataModel.sliceThickness) {
pieChartDataModel.sliceThickness = it
}
AddOrRemoveSliceRow(pieChartDataModel)
}
}
@Composable
private fun PieChartRow(pieChartDataModel: PieChartDataModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(150.dp)
.padding(vertical = Margins.vertical)
) {
PieChart(
pieChartData = pieChartDataModel.pieChartData,
sliceDrawer = SimpleSliceDrawer(
sliceThickness = pieChartDataModel.sliceThickness
)
)
}
}
@Composable
private fun SliceThicknessRow(sliceThickness: Float, onValueUpdated: (Float) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = Margins.verticalLarge),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Slice thickness",
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(end = Margins.horizontal)
)
Slider(
value = sliceThickness,
onValueChange = { onValueUpdated(it) },
valueRange = 10f.rangeTo(100f)
)
}
}
@Composable
private fun AddOrRemoveSliceRow(pieChartDataModel: PieChartDataModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = Margins.vertical),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Button(
enabled = pieChartDataModel.slices.size > 3,
onClick = { pieChartDataModel.removeSlice() },
shape = CircleShape
) {
Icon(Icons.Filled.Remove, contentDescription = "Remove slice from pie chart")
}
Row(
modifier = Modifier.padding(horizontal = Margins.horizontal),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Slices: ")
Text(
text = pieChartDataModel.slices.count().toString(),
style = TextStyle(
fontWeight = FontWeight.ExtraBold,
fontSize = 18.sp
)
)
}
Button(
enabled = pieChartDataModel.slices.size < 9,
onClick = { pieChartDataModel.addSlice() },
shape = CircleShape
) {
Icon(Icons.Filled.Add, contentDescription = "Add slice to pie chart")
}
}
}
@Preview
@Composable
fun PieChartScreenPreview() = PieChartScreen()
@@ -0,0 +1,59 @@
package com.github.tehras.charts.ui.selector
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.github.tehras.charts.theme.Margins
import com.github.tehras.charts.ui.ChartScreen
import com.github.tehras.charts.ui.ChartScreen.Bar
import com.github.tehras.charts.ui.ChartScreen.Line
import com.github.tehras.charts.ui.ChartScreen.Pie
import com.github.tehras.charts.ui.ChartScreenStatus
@Composable
fun SelectChartScreen() {
Scaffold(
topBar = { TopAppBar(title = { Text(text = "Select Chart") }) }
) { SelectChartScreenContent() }
}
@Composable
private fun SelectChartScreenContent() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ChartRow(text = "Pie Chart", navigateTo = Pie)
ChartRow(text = "Bar Chart", navigateTo = Bar)
ChartRow(text = "Line Chart", navigateTo = Line)
}
}
@Composable
private fun ChartRow(
text: String,
navigateTo: ChartScreen
) {
Row(modifier = Modifier.padding(horizontal = Margins.horizontal, vertical = Margins.vertical)) {
TextButton(
onClick = { ChartScreenStatus.navigateTo(navigateTo) }
) {
Text(text = text)
}
}
}
@Preview
@Composable
fun SelectChartScreenPreview() = SelectChartScreen()
@@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="status_bar">#0e0e0e</color>
</resources>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red700">#dd0d3e</color>
<color name="red900">#c20029</color>
<color name="status_bar">@color/red900</color>
</resources>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">charts</string>
</resources>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. In this Jetpack Compose sample app, these colors
don't affect the Composable functions, just the color of the Status Bar.
For the colors used by the Composable functions, see Theme.kt -->
<style name="Theme.Charts" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/red700</item>
<item name="colorPrimaryDark">@color/red900</item>
<item name="colorAccent">@color/red700</item>
<item name="android:statusBarColor">@color/status_bar</item>
</style>
</resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

+29
View File
@@ -0,0 +1,29 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
dependencies {
classpath("com.android.tools.build:gradle:7.3.1")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}")
}
repositories {
google()
gradlePluginPortal()
}
}
subprojects {
repositories {
google()
gradlePluginPortal()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
// Allow warnings when running from IDE, makes it easier to experiment.
allWarningsAsErrors = true
jvmTarget = "1.8"
}
}
}
+3
View File
@@ -0,0 +1,3 @@
plugins { `kotlin-dsl` }
repositories { mavenCentral() }
kotlinDslPluginOptions { experimentalWarning.set(false) }
@@ -0,0 +1,29 @@
@file:JvmName("Deps")
object Versions {
const val kotlin = "1.7.10"
const val composeCompilerVersion = kotlin
const val compose = "1.3.1"
const val targetSdk = 33
const val buildVersion = "33.0.1"
}
object Compose {
const val animation = "androidx.compose.animation:animation:${Versions.compose}"
const val core = "androidx.compose.ui:ui:${Versions.compose}"
const val foundation = "androidx.compose.foundation:foundation:${Versions.compose}"
const val layout = "androidx.compose.foundation:foundation-layout:${Versions.compose}"
const val material = "androidx.compose.material:material:${Versions.compose}"
const val materialIconsExt = "androidx.compose.material:material-icons-extended:${Versions.compose}"
const val runtime = "androidx.compose.runtime:runtime:${Versions.compose}"
const val tooling = "androidx.compose.ui:ui-tooling:${Versions.compose}"
}
object Android {
const val activityCompose = "androidx.activity:activity-compose:1.6.1"
const val appcompat = "androidx.appcompat:appcompat:1.5.1"
}
object Kotlin {
const val stdLib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
+21
View File
@@ -0,0 +1,21 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
@@ -0,0 +1,22 @@
android {
compileSdkVersion Versions.targetSdk
buildToolsVersion Versions.buildVersion
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion 21
targetSdkVersion Versions.targetSdk
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
@@ -0,0 +1,19 @@
android {
buildFeatures { compose true }
// Set both the Java and Kotlin compilers to target Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
composeOptions {
kotlinCompilerVersion Versions.composeCompilerVersion
kotlinCompilerExtensionVersion Versions.compose
}
}
@@ -0,0 +1,11 @@
afterEvaluate {
publishing {
publications {
release(MavenPublication) {
from components.release
groupId = "com.github.tehras.charts"
// TODO artifactId = module.getName()
}
}
}
}
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
#Sat Jun 13 09:37:52 PDT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1
View File
@@ -0,0 +1 @@
jdk: openjdk11
+1
View File
@@ -0,0 +1 @@
/build
+26
View File
@@ -0,0 +1,26 @@
plugins {
id("com.android.library")
kotlin("android")
`maven-publish`
}
apply(from = rootProject.file("gradle/configure-android.gradle"))
apply(from = rootProject.file("gradle/configure-compose.gradle"))
apply(from = rootProject.file("gradle/jitpack-publish.gradle"))
dependencies {
api(project(":lib:common"))
implementation(Kotlin.stdLib)
implementation(Compose.animation)
implementation(Compose.core)
implementation(Compose.layout)
implementation(Compose.foundation)
implementation(Compose.material)
implementation(Compose.runtime)
debugImplementation(Compose.tooling)
}
android {
namespace = "com.github.tehras.charts.bar"
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
@@ -0,0 +1,124 @@
package com.github.tehras.charts.bar
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import com.github.tehras.charts.bar.BarChartUtils.axisAreas
import com.github.tehras.charts.bar.BarChartUtils.barDrawableArea
import com.github.tehras.charts.bar.BarChartUtils.forEachWithArea
import com.github.tehras.charts.bar.renderer.bar.BarDrawer
import com.github.tehras.charts.bar.renderer.bar.SimpleBarDrawer
import com.github.tehras.charts.bar.renderer.label.LabelDrawer
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer
import com.github.tehras.charts.bar.renderer.xaxis.SimpleXAxisDrawer
import com.github.tehras.charts.bar.renderer.xaxis.XAxisDrawer
import com.github.tehras.charts.bar.renderer.yaxis.SimpleYAxisDrawer
import com.github.tehras.charts.bar.renderer.yaxis.YAxisDrawer
import com.github.tehras.charts.piechart.animation.simpleChartAnimation
@Composable
fun BarChart(
barChartData: BarChartData,
modifier: Modifier = Modifier,
animation: AnimationSpec<Float> = simpleChartAnimation(),
barDrawer: BarDrawer = SimpleBarDrawer(),
xAxisDrawer: XAxisDrawer = SimpleXAxisDrawer(),
yAxisDrawer: YAxisDrawer = SimpleYAxisDrawer(),
labelDrawer: LabelDrawer = SimpleValueDrawer()
) {
val transitionAnimation = remember(barChartData.bars) { Animatable(initialValue = 0f) }
LaunchedEffect(barChartData.bars) {
transitionAnimation.animateTo(1f, animationSpec = animation)
}
val progress = transitionAnimation.value
Canvas(modifier = modifier
.fillMaxSize()
.drawBehind {
drawIntoCanvas { canvas ->
val (xAxisArea, yAxisArea) = axisAreas(
drawScope = this,
totalSize = size,
xAxisDrawer = xAxisDrawer,
labelDrawer = labelDrawer
)
val barDrawableArea = barDrawableArea(xAxisArea)
// Draw yAxis line.
yAxisDrawer.drawAxisLine(
drawScope = this,
canvas = canvas,
drawableArea = yAxisArea
)
// Draw xAxis line.
xAxisDrawer.drawAxisLine(
drawScope = this,
canvas = canvas,
drawableArea = xAxisArea
)
// Draw each bar.
barChartData.forEachWithArea(
this,
barDrawableArea,
progress,
labelDrawer
) { barArea, bar ->
barDrawer.drawBar(
drawScope = this,
canvas = canvas,
barArea = barArea,
bar = bar
)
}
}
}
) {
/**
* Typically we could draw everything here, but because of the lack of canvas.drawText
* APIs we have to use Android's `nativeCanvas` which seems to be drawn behind
* Compose's canvas.
*/
drawIntoCanvas { canvas ->
val (xAxisArea, yAxisArea) = axisAreas(
drawScope = this,
totalSize = size,
xAxisDrawer = xAxisDrawer,
labelDrawer = labelDrawer
)
val barDrawableArea = barDrawableArea(xAxisArea)
barChartData.forEachWithArea(
this,
barDrawableArea,
progress,
labelDrawer
) { barArea, bar ->
labelDrawer.drawLabel(
drawScope = this,
canvas = canvas,
label = bar.label,
barArea = barArea,
xAxisArea = xAxisArea
)
}
yAxisDrawer.drawAxisLabels(
drawScope = this,
canvas = canvas,
minValue = barChartData.minYValue,
maxValue = barChartData.maxYValue,
drawableArea = yAxisArea
)
}
}
}
@@ -0,0 +1,39 @@
package com.github.tehras.charts.bar
import androidx.compose.ui.graphics.Color
data class BarChartData(
val bars: List<Bar>,
val padBy: Float = 10f,
val startAtZero: Boolean = true
) {
init {
require(padBy in 0f..100f)
}
private val yMinMax: Pair<Float, Float>
get() {
val min = bars.minByOrNull { it.value }?.value ?: 0f
val max = bars.maxByOrNull { it.value }?.value ?: 0f
return min to max
}
internal val maxYValue: Float =
yMinMax.second + ((yMinMax.second - yMinMax.first) * padBy / 100f)
internal val minYValue: Float
get() {
return if (startAtZero) {
0f
} else {
yMinMax.first - ((yMinMax.second - yMinMax.first) * padBy / 100f)
}
}
val maxBarValue = bars.maxByOrNull { it.value }?.value ?: 0f
data class Bar(
val value: Float,
val color: Color,
val label: String
)
}
@@ -0,0 +1,71 @@
package com.github.tehras.charts.bar
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.dp
import com.github.tehras.charts.bar.renderer.label.LabelDrawer
import com.github.tehras.charts.bar.renderer.xaxis.XAxisDrawer
internal object BarChartUtils {
fun axisAreas(
drawScope: DrawScope,
totalSize: Size,
xAxisDrawer: XAxisDrawer,
labelDrawer: LabelDrawer
): Pair<Rect, Rect> = with(drawScope) {
// yAxis
val yAxisTop = labelDrawer.requiredAboveBarHeight(drawScope)
// Either 50dp or 10% of the chart width.
val yAxisRight = minOf(50.dp.toPx(), size.width * 10f / 100f)
// xAxis
val xAxisRight = totalSize.width
// Measure the size of the text and line.
val xAxisTop = totalSize.height - xAxisDrawer.requiredHeight(drawScope)
return Pair(
Rect(yAxisRight, xAxisTop, xAxisRight, totalSize.height),
Rect(0f, yAxisTop, yAxisRight, xAxisTop)
)
}
fun barDrawableArea(xAxisArea: Rect): Rect {
return Rect(
left = xAxisArea.left,
top = 0f,
right = xAxisArea.right,
bottom = xAxisArea.top
)
}
fun BarChartData.forEachWithArea(
drawScope: DrawScope,
barDrawableArea: Rect,
progress: Float,
labelDrawer: LabelDrawer,
block: (barArea: Rect, bar: BarChartData.Bar) -> Unit
) {
val totalBars = bars.size
val widthOfBarArea = barDrawableArea.width / totalBars
val offsetOfBar = widthOfBarArea * 0.2f
bars.forEachIndexed { index, bar ->
val left = barDrawableArea.left + (index * widthOfBarArea)
val height = barDrawableArea.height
val barHeight = (height - labelDrawer.requiredAboveBarHeight(drawScope)) * progress
val barArea = Rect(
left = left + offsetOfBar,
top = barDrawableArea.bottom - (bar.value / maxBarValue) * barHeight,
right = left + widthOfBarArea - offsetOfBar,
bottom = barDrawableArea.bottom
)
block(barArea, bar)
}
}
}
@@ -0,0 +1,15 @@
package com.github.tehras.charts.bar.renderer.bar
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import com.github.tehras.charts.bar.BarChartData
interface BarDrawer {
fun drawBar(
drawScope: DrawScope,
canvas: Canvas,
barArea: Rect,
bar: BarChartData.Bar
)
}
@@ -0,0 +1,24 @@
package com.github.tehras.charts.bar.renderer.bar
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.drawscope.DrawScope
import com.github.tehras.charts.bar.BarChartData
class SimpleBarDrawer : BarDrawer {
private val barPaint = Paint().apply {
this.isAntiAlias = true
}
override fun drawBar(
drawScope: DrawScope,
canvas: Canvas,
barArea: Rect,
bar: BarChartData.Bar
) {
canvas.drawRect(barArea, barPaint.apply {
color = bar.color
})
}
}
@@ -0,0 +1,18 @@
package com.github.tehras.charts.bar.renderer.label
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface LabelDrawer {
fun requiredXAxisHeight(drawScope: DrawScope): Float = 0f
fun requiredAboveBarHeight(drawScope: DrawScope): Float = 0f
fun drawLabel(
drawScope: DrawScope,
canvas: Canvas,
label: String,
barArea: Rect,
xAxisArea: Rect
)
}
@@ -0,0 +1,71 @@
package com.github.tehras.charts.bar.renderer.label
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.Inside
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.Outside
import com.github.tehras.charts.bar.renderer.label.SimpleValueDrawer.DrawLocation.XAxis
import com.github.tehras.charts.piechart.utils.toLegacyInt
class SimpleValueDrawer(
private val drawLocation: DrawLocation = Inside,
private val labelTextSize: TextUnit = 12.sp,
private val labelTextColor: Color = Color.Black
) : LabelDrawer {
private val _labelTextArea: Float? = null
private val paint = android.graphics.Paint().apply {
this.textAlign = android.graphics.Paint.Align.CENTER
this.color = labelTextColor.toLegacyInt()
}
override fun requiredAboveBarHeight(drawScope: DrawScope): Float = when (drawLocation) {
Outside -> (3f / 2f) * labelTextHeight(drawScope)
Inside,
XAxis -> 0f
}
override fun requiredXAxisHeight(drawScope: DrawScope): Float = when (drawLocation) {
XAxis -> labelTextHeight(drawScope)
Inside,
Outside -> 0f
}
override fun drawLabel(
drawScope: DrawScope,
canvas: Canvas,
label: String,
barArea: Rect,
xAxisArea: Rect
) = with(drawScope) {
val xCenter = barArea.left + (barArea.width / 2)
val yCenter = when (drawLocation) {
Inside -> (barArea.top + barArea.bottom) / 2
Outside -> (barArea.top) - labelTextSize.toPx() / 2
XAxis -> barArea.bottom + labelTextHeight(drawScope)
}
canvas.nativeCanvas.drawText(label, xCenter, yCenter, paint(drawScope))
}
private fun labelTextHeight(drawScope: DrawScope) = with(drawScope) {
_labelTextArea ?: ((3f / 2f) * labelTextSize.toPx())
}
private fun paint(drawScope: DrawScope) = with(drawScope) {
paint.apply {
this.textSize = labelTextSize.toPx()
}
}
enum class DrawLocation {
Inside,
Outside,
XAxis
}
}
@@ -0,0 +1,46 @@
package com.github.tehras.charts.bar.renderer.xaxis
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
class SimpleXAxisDrawer(
private val axisLineThickness: Dp = 1.dp,
private val axisLineColor: Color = Color.Black
) : XAxisDrawer {
private val axisLinePaint = Paint().apply {
isAntiAlias = true
color = axisLineColor
style = PaintingStyle.Stroke
}
override fun requiredHeight(drawScope: DrawScope): Float = with(drawScope) {
(3f / 2f) * axisLineThickness.toPx()
}
override fun drawAxisLine(drawScope: DrawScope, canvas: Canvas, drawableArea: Rect) =
with(drawScope) {
val lineThickness = axisLineThickness.toPx()
val y = drawableArea.top + (lineThickness / 2f)
canvas.drawLine(
p1 = Offset(
x = drawableArea.left,
y = y
),
p2 = Offset(
x = drawableArea.right,
y = y
),
paint = axisLinePaint.apply {
strokeWidth = lineThickness
}
)
}
}
@@ -0,0 +1,15 @@
package com.github.tehras.charts.bar.renderer.xaxis
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface XAxisDrawer {
fun requiredHeight(drawScope: DrawScope): Float
fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
)
}
@@ -0,0 +1,92 @@
package com.github.tehras.charts.bar.renderer.yaxis
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.piechart.utils.toLegacyInt
import kotlin.math.max
import kotlin.math.roundToInt
typealias LabelFormatter = (value: Float) -> String
class SimpleYAxisDrawer(
private val labelTextSize: TextUnit = 12.sp,
private val labelTextColor: Color = Color.Black,
private val labelRatio: Int = 3,
private val labelValueFormatter: LabelFormatter = { value -> "%.1f".format(value) },
private val axisLineThickness: Dp = 1.dp,
private val axisLineColor: Color = Color.Black
) : YAxisDrawer {
private val axisLinePaint = Paint().apply {
isAntiAlias = true
color = axisLineColor
style = PaintingStyle.Stroke
}
private val textPaint = android.graphics.Paint().apply {
isAntiAlias = true
color = labelTextColor.toLegacyInt()
}
private val textBounds = android.graphics.Rect()
override fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
) = with(drawScope) {
val lineThickness = axisLineThickness.toPx()
val x = drawableArea.right - (lineThickness / 2f)
canvas.drawLine(
p1 = Offset(
x = x,
y = drawableArea.top
),
p2 = Offset(
x = x,
y = drawableArea.bottom
),
paint = axisLinePaint.apply {
strokeWidth = lineThickness
}
)
}
override fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
minValue: Float,
maxValue: Float
) = with(drawScope) {
val labelPaint = textPaint.apply {
textSize = labelTextSize.toPx()
textAlign = android.graphics.Paint.Align.RIGHT
}
val minLabelHeight = (labelTextSize.toPx() * labelRatio.toFloat())
val totalHeight = drawableArea.height
val labelCount = max((drawableArea.height / minLabelHeight).roundToInt(), 2)
for (i in 0..labelCount) {
val value = minValue + (i * ((maxValue - minValue) / labelCount))
val label = labelValueFormatter(value)
val x = drawableArea.right - axisLineThickness.toPx() - (labelTextSize.toPx() / 2f)
labelPaint.getTextBounds(label, 0, label.length, textBounds)
val y =
drawableArea.bottom - (i * (totalHeight / labelCount)) + (textBounds.height() / 2f)
canvas.nativeCanvas.drawText(label, x, y, labelPaint)
}
}
}
@@ -0,0 +1,21 @@
package com.github.tehras.charts.bar.renderer.yaxis
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface YAxisDrawer {
fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
)
fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
minValue: Float,
maxValue: Float
)
}
+1
View File
@@ -0,0 +1 @@
/build
+23
View File
@@ -0,0 +1,23 @@
plugins {
id("com.android.library")
kotlin("android")
`maven-publish`
}
apply(from = rootProject.file("gradle/configure-android.gradle"))
apply(from = rootProject.file("gradle/configure-compose.gradle"))
apply(from = rootProject.file("gradle/jitpack-publish.gradle"))
dependencies {
implementation(Kotlin.stdLib)
implementation(Compose.animation)
implementation(Compose.core)
implementation(Compose.layout)
implementation(Compose.foundation)
implementation(Compose.runtime)
debugImplementation(Compose.tooling)
}
android {
namespace = "com.github.tehras.charts.common"
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
@@ -0,0 +1,22 @@
package com.github.tehras.charts.piechart
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class AxisLine(
val thickness: Dp = 1.5.dp,
val color: Color = Color.Gray
) {
private val paint = Paint().apply {
this.color = this@AxisLine.color
this.style = PaintingStyle.Stroke
}
fun paint(density: Density) = paint.apply {
this.strokeWidth = thickness.value * density.density
}
}
@@ -0,0 +1,5 @@
package com.github.tehras.charts.piechart.animation
import androidx.compose.animation.core.TweenSpec
fun simpleChartAnimation() = TweenSpec<Float>(durationMillis = 500)
@@ -0,0 +1,12 @@
package com.github.tehras.charts.piechart.utils
import androidx.compose.ui.graphics.Color
fun Color.toLegacyInt(): Int {
return android.graphics.Color.argb(
(alpha * 255.0f + 0.5f).toInt(),
(red * 255.0f + 0.5f).toInt(),
(green * 255.0f + 0.5f).toInt(),
(blue * 255.0f + 0.5f).toInt()
)
}
+1
View File
@@ -0,0 +1 @@
/build
+25
View File
@@ -0,0 +1,25 @@
plugins {
id("com.android.library")
kotlin("android")
`maven-publish`
}
apply(from = rootProject.file("gradle/configure-android.gradle"))
apply(from = rootProject.file("gradle/configure-compose.gradle"))
apply(from = rootProject.file("gradle/jitpack-publish.gradle"))
dependencies {
api(project(":lib:common"))
implementation(Kotlin.stdLib)
implementation(Compose.animation)
implementation(Compose.core)
implementation(Compose.layout)
implementation(Compose.foundation)
implementation(Compose.runtime)
debugImplementation(Compose.tooling)
}
android {
namespace = "com.github.tehras.charts.line"
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest>
</manifest>
@@ -0,0 +1,188 @@
package com.github.tehras.charts.line
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import com.github.tehras.charts.line.LineChartUtils.calculateDrawableArea
import com.github.tehras.charts.line.LineChartUtils.calculateFillPath
import com.github.tehras.charts.line.LineChartUtils.calculateLinePath
import com.github.tehras.charts.line.LineChartUtils.calculatePointLocation
import com.github.tehras.charts.line.LineChartUtils.calculateXAxisDrawableArea
import com.github.tehras.charts.line.LineChartUtils.calculateXAxisLabelsDrawableArea
import com.github.tehras.charts.line.LineChartUtils.calculateYAxisDrawableArea
import com.github.tehras.charts.line.LineChartUtils.withProgress
import com.github.tehras.charts.line.renderer.line.LineDrawer
import com.github.tehras.charts.line.renderer.line.LineShader
import com.github.tehras.charts.line.renderer.line.NoLineShader
import com.github.tehras.charts.line.renderer.line.SolidLineDrawer
import com.github.tehras.charts.line.renderer.point.FilledCircularPointDrawer
import com.github.tehras.charts.line.renderer.point.PointDrawer
import com.github.tehras.charts.line.renderer.xaxis.SimpleXAxisDrawer
import com.github.tehras.charts.line.renderer.xaxis.XAxisDrawer
import com.github.tehras.charts.line.renderer.yaxis.SimpleYAxisDrawer
import com.github.tehras.charts.line.renderer.yaxis.YAxisDrawer
import com.github.tehras.charts.piechart.animation.simpleChartAnimation
@Composable
fun LineChart(
modifier: Modifier = Modifier,
linesChartData: List<LineChartData>,
labels: List<String> = linesChartData.maxByOrNull { it.points.size }?.points?.map { it.label }
?: emptyList(),
animation: AnimationSpec<Float> = simpleChartAnimation(),
pointDrawer: PointDrawer = FilledCircularPointDrawer(),
lineShader: LineShader = NoLineShader,
xAxisDrawer: XAxisDrawer = SimpleXAxisDrawer(),
yAxisDrawer: YAxisDrawer = SimpleYAxisDrawer(),
horizontalOffset: Float = 5f
) {
check(horizontalOffset in 0f..25f) {
"Horizontal offset is the % offset from sides, " +
"and should be between 0%-25%"
}
val transitionAnimation = remember(linesChartData.forEach { it.points }) {
mutableStateListOf(
*linesChartData.map { Animatable(0f) }.toTypedArray()
)
}
LaunchedEffect(linesChartData.forEach { it.points }) {
repeat(linesChartData.size) { index ->
transitionAnimation[index].snapTo(0f)
transitionAnimation[index].animateTo(
targetValue = 1f,
animationSpec = animation
)
}
}
Canvas(modifier = modifier.fillMaxSize()) {
drawIntoCanvas { canvas ->
val yAxisDrawableArea = calculateYAxisDrawableArea(
xAxisLabelSize = xAxisDrawer.requiredHeight(this),
size = size
)
val xAxisDrawableArea = calculateXAxisDrawableArea(
yAxisWidth = yAxisDrawableArea.width,
labelHeight = xAxisDrawer.requiredHeight(this),
size = size
)
val xAxisLabelsDrawableArea = calculateXAxisLabelsDrawableArea(
xAxisDrawableArea = xAxisDrawableArea,
offset = horizontalOffset
)
val chartDrawableArea = calculateDrawableArea(
xAxisDrawableArea = xAxisDrawableArea,
yAxisDrawableArea = yAxisDrawableArea,
size = size,
offset = horizontalOffset
)
// Draw the X Axis line.
xAxisDrawer.drawAxisLine(
drawScope = this,
drawableArea = xAxisDrawableArea,
canvas = canvas
)
xAxisDrawer.drawAxisLabels(
drawScope = this,
canvas = canvas,
drawableArea = xAxisLabelsDrawableArea,
labels = labels
)
// Draw the Y Axis line.
yAxisDrawer.drawAxisLine(
drawScope = this,
canvas = canvas,
drawableArea = yAxisDrawableArea
)
yAxisDrawer.drawAxisLabels(
drawScope = this,
canvas = canvas,
drawableArea = yAxisDrawableArea,
minValue = linesChartData.minOf { it.minYValue },
maxValue = linesChartData.maxOf { it.maxYValue }
)
linesChartData.forEachIndexed { index, lineChartData ->
drawLine(
canvas = canvas,
lineChartData = lineChartData,
transitionAnimation = transitionAnimation[index],
pointDrawer = pointDrawer,
lineDrawer = lineChartData.lineDrawer,
lineShader = lineShader,
chartDrawableArea = chartDrawableArea
)
}
}
}
}
private fun DrawScope.drawLine(
pointDrawer: PointDrawer = FilledCircularPointDrawer(),
lineDrawer: LineDrawer = SolidLineDrawer(),
lineShader: LineShader = NoLineShader,
canvas: Canvas,
transitionAnimation: Animatable<Float, AnimationVector1D>,
lineChartData: LineChartData,
chartDrawableArea: Rect
) {
// Draw the chart line.
lineDrawer.drawLine(
drawScope = this,
canvas = canvas,
linePath = calculateLinePath(
drawableArea = chartDrawableArea,
lineChartData = lineChartData,
transitionProgress = transitionAnimation.value
)
)
lineShader.fillLine(
drawScope = this,
canvas = canvas,
fillPath = calculateFillPath(
drawableArea = chartDrawableArea,
lineChartData = lineChartData,
transitionProgress = transitionAnimation.value
)
)
lineChartData.points.forEachIndexed { index, point ->
withProgress(
index = index,
lineChartData = lineChartData,
transitionProgress = transitionAnimation.value
) {
pointDrawer.drawPoint(
drawScope = this,
canvas = canvas,
center = calculatePointLocation(
drawableArea = chartDrawableArea,
lineChartData = lineChartData,
point = point,
index = index
)
)
}
}
}
@@ -0,0 +1,37 @@
package com.github.tehras.charts.line
import com.github.tehras.charts.line.renderer.line.LineDrawer
data class LineChartData(
val points: List<Point>,
/** This is percentage we pad yValue by.**/
val padBy: Float = 20f,
val startAtZero: Boolean = false,
val lineDrawer: LineDrawer,
) {
init {
require(padBy in 0f..100f)
}
private val yMinMax: Pair<Float, Float>
get() {
val min = points.minByOrNull { it.value }?.value ?: 0f
val max = points.maxByOrNull { it.value }?.value ?: 0f
return min to max
}
internal val maxYValue: Float =
yMinMax.second + ((yMinMax.second - yMinMax.first) * padBy / 100f)
internal val minYValue: Float
get() {
return if (startAtZero) {
0f
} else {
yMinMax.first - ((yMinMax.second - yMinMax.first) * padBy / 100f)
}
}
internal val yRange = maxYValue - minYValue
data class Point(val value: Float, val label: String)
}
@@ -0,0 +1,205 @@
package com.github.tehras.charts.line
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
object LineChartUtils {
fun calculateDrawableArea(
xAxisDrawableArea: Rect,
yAxisDrawableArea: Rect,
size: Size,
offset: Float
): Rect {
val horizontalOffset = xAxisDrawableArea.width * offset / 100f
return Rect(
left = yAxisDrawableArea.right + horizontalOffset,
top = 0f,
bottom = xAxisDrawableArea.top,
right = size.width - horizontalOffset
)
}
fun calculateXAxisDrawableArea(
yAxisWidth: Float,
labelHeight: Float,
size: Size
): Rect {
val top = size.height - labelHeight
return Rect(
left = yAxisWidth,
top = top,
bottom = size.height,
right = size.width
)
}
fun calculateXAxisLabelsDrawableArea(
xAxisDrawableArea: Rect,
offset: Float
): Rect {
val horizontalOffset = xAxisDrawableArea.width * offset / 100f
return Rect(
left = xAxisDrawableArea.left + horizontalOffset,
top = xAxisDrawableArea.top,
bottom = xAxisDrawableArea.bottom,
right = xAxisDrawableArea.right - horizontalOffset
)
}
fun Density.calculateYAxisDrawableArea(
xAxisLabelSize: Float,
size: Size
): Rect {
// Either 50dp or 10% of the chart width.
val right = minOf(50.dp.toPx(), size.width * 10f / 100f)
return Rect(
left = 0f,
top = 0f,
bottom = size.height - xAxisLabelSize,
right = right
)
}
fun calculatePointLocation(
drawableArea: Rect,
lineChartData: LineChartData,
point: LineChartData.Point,
index: Int
): Offset {
val x = (index.toFloat() / (lineChartData.points.size - 1))
val y = ((point.value - lineChartData.minYValue) / lineChartData.yRange)
return Offset(
x = (x * drawableArea.width) + drawableArea.left,
y = drawableArea.height - (y * drawableArea.height)
)
}
fun withProgress(
index: Int,
lineChartData: LineChartData,
transitionProgress: Float,
showWithProgress: (progress: Float) -> Unit
) {
val size = lineChartData.points.size
val toIndex = (size * transitionProgress).toInt() + 1
if (index == toIndex) {
// Get the left over.
val sizeF = lineChartData.points.size.toFloat()
val perIndex = (1f / sizeF)
val down = (index - 1) * perIndex
showWithProgress((transitionProgress - down) / perIndex)
} else if (index < toIndex) {
showWithProgress(1f)
}
}
fun calculateLinePath(
drawableArea: Rect,
lineChartData: LineChartData,
transitionProgress: Float
): Path = Path().apply {
var prevPointLocation: Offset? = null
lineChartData.points.forEachIndexed { index, point ->
withProgress(
index = index,
transitionProgress = transitionProgress,
lineChartData = lineChartData
) { progress ->
val pointLocation = calculatePointLocation(
drawableArea = drawableArea,
lineChartData = lineChartData,
point = point,
index = index
)
if (pointLocation.isSpecified) {
if (index == 0) {
moveTo(pointLocation.x, pointLocation.y)
} else {
if (progress <= 1f) {
// We have to change the `dy` based on the progress
val prevX = prevPointLocation!!.x
val prevY = prevPointLocation!!.y
val x = (pointLocation.x - prevX) * progress + prevX
val y = (pointLocation.y - prevY) * progress + prevY
lineTo(x, y)
} else {
lineTo(pointLocation.x, pointLocation.y)
}
}
prevPointLocation = pointLocation
}
}
}
}
fun calculateFillPath(drawableArea: Rect,
lineChartData: LineChartData,
transitionProgress: Float
): Path = Path().apply {
// we start from the bottom left
moveTo(drawableArea.left, drawableArea.bottom)
var prevPointX : Float? = null
var prevPointLocation: Offset? = null
lineChartData.points.forEachIndexed { index, point ->
withProgress(
index = index,
transitionProgress = transitionProgress,
lineChartData = lineChartData
) { progress ->
val pointLocation = calculatePointLocation(
drawableArea = drawableArea,
lineChartData = lineChartData,
point = point,
index = index
)
if (pointLocation.isSpecified) {
if (index == 0) {
lineTo(drawableArea.left, pointLocation.y)
lineTo(pointLocation.x, pointLocation.y)
} else {
if (progress <= 1f) {
// We have to change the `dy` based on the progress
val prevX = prevPointLocation!!.x
val prevY = prevPointLocation!!.y
val x = (pointLocation.x - prevX) * progress + prevX
val y = (pointLocation.y - prevY) * progress + prevY
lineTo(x, y)
prevPointX = x
} else {
lineTo(pointLocation.x, pointLocation.y)
prevPointX = pointLocation.x
}
}
prevPointLocation = pointLocation
}
}
}
// We need to connect the line to the end of the drawable area
prevPointX?.let { x->
lineTo(x, drawableArea.bottom)
lineTo(drawableArea.right, drawableArea.bottom)
} ?: lineTo(drawableArea.left, drawableArea.bottom)
}
}
@@ -0,0 +1,17 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
class GradientLineShader(colors: List<Color> = listOf(Color.Blue, Color.Transparent)) : LineShader {
private val brush = Brush.verticalGradient(colors)
override fun fillLine(drawScope: DrawScope, canvas: Canvas, fillPath: Path) {
drawScope.drawPath(
path = fillPath,
brush = brush
)
}
}
@@ -0,0 +1,13 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
interface LineDrawer {
fun drawLine(
drawScope: DrawScope,
canvas: Canvas,
linePath: Path
)
}
@@ -0,0 +1,13 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
interface LineShader {
fun fillLine(
drawScope: DrawScope,
canvas: Canvas,
fillPath: Path
)
}
@@ -0,0 +1,11 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
object NoLineShader : LineShader {
override fun fillLine(drawScope: DrawScope, canvas: Canvas, fillPath: Path) {
// Do nothing
}
}
@@ -0,0 +1,34 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class SolidLineDrawer(
val thickness: Dp = 3.dp,
val color: Color = Color.Cyan
) : LineDrawer {
private val paint = Paint().apply {
this.color = this@SolidLineDrawer.color
this.style = PaintingStyle.Stroke
this.isAntiAlias = true
}
override fun drawLine(
drawScope: DrawScope,
canvas: Canvas,
linePath: Path
) {
val lineThickness = with(drawScope) {
thickness.toPx()
}
canvas.drawPath(
path = linePath,
paint = paint.apply {
strokeWidth = lineThickness
}
)
}
}
@@ -0,0 +1,15 @@
package com.github.tehras.charts.line.renderer.line
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
class SolidLineShader(val color: Color = Color.Blue) : LineShader {
override fun fillLine(drawScope: DrawScope, canvas: Canvas, fillPath: Path) {
drawScope.drawPath(
path = fillPath,
color = color
)
}
}
@@ -0,0 +1,33 @@
package com.github.tehras.charts.line.renderer.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class FilledCircularPointDrawer(
val diameter: Dp = 8.dp,
val color: Color = Color.Blue
) : PointDrawer {
private val paint = Paint().apply {
color = this@FilledCircularPointDrawer.color
style = PaintingStyle.Fill
isAntiAlias = true
}
override fun drawPoint(
drawScope: DrawScope,
canvas: Canvas,
center: Offset
) {
with(drawScope as Density) {
canvas.drawCircle(center, diameter.toPx() / 2f, paint)
}
}
}
@@ -0,0 +1,40 @@
package com.github.tehras.charts.line.renderer.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class HollowCircularPointDrawer(
val diameter: Dp = 8.dp,
val lineThickness: Dp = 2.dp,
val color: Color = Color.Blue
) : PointDrawer {
private val paint = Paint().apply {
color = this@HollowCircularPointDrawer.color
style = PaintingStyle.Stroke
isAntiAlias = true
}
override fun drawPoint(
drawScope: DrawScope,
canvas: Canvas,
center: Offset
) {
with(drawScope as Density) {
canvas.drawCircle(
center = center,
radius = diameter.toPx() / 2f,
paint = paint.apply {
strokeWidth = lineThickness.toPx()
}
)
}
}
}
@@ -0,0 +1,15 @@
package com.github.tehras.charts.line.renderer.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
object NoPointDrawer : PointDrawer {
override fun drawPoint(
drawScope: DrawScope,
canvas: Canvas,
center: Offset
) {
// Leave empty on purpose, we do not want to draw anything.
}
}
@@ -0,0 +1,13 @@
package com.github.tehras.charts.line.renderer.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface PointDrawer {
fun drawPoint(
drawScope: DrawScope,
canvas: Canvas,
center: Offset
)
}
@@ -0,0 +1,90 @@
package com.github.tehras.charts.line.renderer.xaxis
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.piechart.utils.toLegacyInt
class SimpleXAxisDrawer(
private val labelTextSize: TextUnit = 12.sp,
private val labelTextColor: Color = Color.Black,
/** 1 means we draw everything. 2 means we draw every other, and so on. */
private val labelRatio: Int = 1,
private val axisLineThickness: Dp = 1.dp,
private val axisLineColor: Color = Color.Black
) : XAxisDrawer {
private val axisLinePaint = Paint().apply {
isAntiAlias = true
color = axisLineColor
style = PaintingStyle.Stroke
}
private val textPaint = android.graphics.Paint().apply {
isAntiAlias = true
color = labelTextColor.toLegacyInt()
}
override fun requiredHeight(drawScope: DrawScope): Float {
return with(drawScope) {
(3f / 2f) * (labelTextSize.toPx() + axisLineThickness.toPx())
}
}
override fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
) {
with(drawScope) {
val lineThickness = axisLineThickness.toPx()
val y = drawableArea.top + (lineThickness / 2f)
canvas.drawLine(
p1 = Offset(
x = drawableArea.left,
y = y
),
p2 = Offset(
x = drawableArea.right,
y = y
),
paint = axisLinePaint.apply {
strokeWidth = lineThickness
}
)
}
}
override fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
labels: List<String>
) {
with(drawScope) {
val labelPaint = textPaint.apply {
textSize = labelTextSize.toPx()
textAlign = android.graphics.Paint.Align.CENTER
}
val labelIncrements = drawableArea.width / (labels.size - 1)
labels.forEachIndexed { index, label ->
if (index.rem(labelRatio) == 0) {
val x = drawableArea.left + (labelIncrements * (index))
val y = drawableArea.bottom
canvas.nativeCanvas.drawText(label, x, y, labelPaint)
}
}
}
}
}
@@ -0,0 +1,22 @@
package com.github.tehras.charts.line.renderer.xaxis
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface XAxisDrawer {
fun requiredHeight(drawScope: DrawScope): Float
fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
)
fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
labels: List<String>
)
}
@@ -0,0 +1,93 @@
package com.github.tehras.charts.line.renderer.yaxis
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.github.tehras.charts.piechart.utils.toLegacyInt
import kotlin.math.max
import kotlin.math.roundToInt
typealias LabelFormatter = (value: Float) -> String
class SimpleYAxisDrawer(
private val labelTextSize: TextUnit = 12.sp,
private val labelTextColor: Color = Color.Black,
private val labelRatio: Int = 3,
private val labelValueFormatter: LabelFormatter = { value -> "%.1f".format(value) },
private val axisLineThickness: Dp = 1.dp,
private val axisLineColor: Color = Color.Black
) : YAxisDrawer {
private val axisLinePaint = Paint().apply {
isAntiAlias = true
color = axisLineColor
style = PaintingStyle.Stroke
}
private val textPaint = android.graphics.Paint().apply {
isAntiAlias = true
color = labelTextColor.toLegacyInt()
}
private val textBounds = android.graphics.Rect()
override fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
) = with(drawScope) {
val lineThickness = axisLineThickness.toPx()
val x = drawableArea.right - (lineThickness / 2f)
canvas.drawLine(
p1 = Offset(
x = x,
y = drawableArea.top
),
p2 = Offset(
x = x,
y = drawableArea.bottom
),
paint = axisLinePaint.apply {
strokeWidth = lineThickness
}
)
}
override fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
minValue: Float,
maxValue: Float
) = with(drawScope) {
val labelPaint = textPaint.apply {
textSize = labelTextSize.toPx()
textAlign = android.graphics.Paint.Align.RIGHT
}
val minLabelHeight = (labelTextSize.toPx() * labelRatio.toFloat())
val totalHeight = drawableArea.height
val labelCount = max((drawableArea.height / minLabelHeight).roundToInt(), 2)
for (i in 0..labelCount) {
val value = minValue + (i * ((maxValue - minValue) / labelCount))
val label = labelValueFormatter(value)
val x =
drawableArea.right - axisLineThickness.toPx() - (labelTextSize.toPx() / 2f)
labelPaint.getTextBounds(label, 0, label.length, textBounds)
val y =
drawableArea.bottom - (i * (totalHeight / labelCount)) + (textBounds.height() / 2f)
canvas.nativeCanvas.drawText(label, x, y, labelPaint)
}
}
}
@@ -0,0 +1,21 @@
package com.github.tehras.charts.line.renderer.yaxis
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
interface YAxisDrawer {
fun drawAxisLine(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect
)
fun drawAxisLabels(
drawScope: DrawScope,
canvas: Canvas,
drawableArea: Rect,
minValue: Float,
maxValue: Float
)
}

Some files were not shown because too many files have changed in this diff Show More