막무가내 삽질 블로그

안드로이드 그래프 (android MPAndroidChart) 본문

Android

안드로이드 그래프 (android MPAndroidChart)

joong~ 2020. 11. 6. 17:03
728x90

 

프로젝트에 그래프가 있어서 MPAndroidChart라이브러리를 사용하면서 내용을 정리봤다.

 

내가 사용할 것은 BarChart와 LineChart다.

 

 

 

프로젝트 이미지

 

프로젝트에 적용할 이미지다.

 

현재 MPAndroidChart는 라운드를 지원하지 않으며 라벨 컬러도 각각 지원하지 않는다. 하고 싶으면 직접 커스텀 해서 사용해야 한다.

 

 

BarChart 정리

        barChart.run {
            setDrawBarShadow(true) // 그래프 그림자
            setTouchEnabled(false) // 차트 터치 막기
            setDrawValueAboveBar(true) // 입력?값이 차트 위or아래에 그려질 건지 (true=위, false=아래)
            setPinchZoom(false) // 두손가락으로 줌 설정
            setDrawGridBackground(false) // 격자구조
            setMaxVisibleValueCount(10) // 그래프 최대 갯수
            description.isEnabled = false // 그래프 오른쪽 하단에 라벨 표시
            legend.isEnabled = false // 차트 범례 설정(legend object chart)

            xAxis.run { // 아래 라벨 x축
                isEnabled = true // 라벨 표시 설정
                position = XAxis.XAxisPosition.BOTTOM // 라벨 위치 설정
                valueFormatter = LabelFormatter() // 라벨 값 포멧 설정
                setDrawGridLines(false) // 격자구조
                granularity = 1f // 간격 설정
                setDrawAxisLine(false) // 그림
                textSize = 12f // 라벨 크기
                textColor = Color.BLUE
            }

            axisLeft.run { // 왼쪽 y축
                isEnabled = false
                axisMinimum = 0f // 최소값
                axisMaximum = 100f // 최대값
                granularity = 10f // 값 만큼 라인선 설정
                setDrawLabels(false) // 값 셋팅 설정
                textColor = Color.RED // 색상 설정
                axisLineColor = Color.BLACK // 축 색상 설정
                gridColor = Color.BLUE // 격자 색상 설정
            }
            axisRight.run { // 오른쪽 y축(왼쪽과동일)
                isEnabled = false
                textSize = 15f
            }

            animateY(1500) // y축 애니메이션
            animateX(1000) // x축 애니메이션
        }

 

임의의 데이터 셋팅

        val values = mutableListOf<BarEntry>()
        val colorList = listOf(
            Color.rgb(192, 255, 140),
            Color.rgb(255, 247, 97),
            Color.rgb(79, 208, 45),
            Color.rgb(140, 234, 255),
            Color.rgb(255, 140, 157)
        )

        for (i in 6..10) {
            val index = i.toFloat()
            val random = Random().nextInt(101).toFloat()

            values.add(BarEntry(index, random))
        }

        val set = BarDataSet(values, "내용없음")
            .apply {
                setDrawIcons(false)
                setDrawValues(true)
                colors = colorList
                valueFormatter = ScoreFormatter()
                valueTextColor = Color.RED
            }

        val dataSets = mutableListOf<IBarDataSet>()
        dataSets.add(set)

        val data = BarData(dataSets)
            .apply {
                setValueTextSize(10f)
                barWidth = 0.5f
            }

        barChart.data = data

 

 

 

 

완성

완성

 

 

getFormattedValue가 deprecated 되어서 스코어 같은 경우는 만들어서 사용해야 한다.

라벨 색상 또한 할려고 하다 너무 안되서 일단 이런식으로 진행하기로 했다.

조금 더 수정 후 다듬고 프로젝트에 붙힐 예정이다

 

class LabelCustomFormatter : ValueFormatter() {
    private var index = 0

    override fun getFormattedValue(value: Float): String {
        index = value.toInt()
        return when (index) {
            6 -> "DR"
            7 -> "WU"
            8 -> "IRON"
            9 -> "S/W"
            10 -> "PUTT"
            else -> throw IndexOutOfBoundsException("index out")
        }
    }

    override fun getBarStackedLabel(value: Float, stackedEntry: BarEntry?): String {
        return super.getBarStackedLabel(value, stackedEntry)
    }
}

class ScoreCustomFormatter : ValueFormatter() {
    override fun getFormattedValue(value: Float): String {
        val score = value.toString().split(".")
        return score[0]+"점"
    }
}

 

 

 

 

 

ps 완성

완성

'Android' 카테고리의 다른 글

Android Context  (2) 2020.12.13
kotlin 요약 정리  (2) 2020.12.09
android flag  (0) 2020.10.30
android ignore folder or file  (0) 2020.10.25
RxJava 마지막주차  (0) 2020.10.18
Comments