Advertisement
andyshon

WhoGraphNewActivity

Sep 20th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 31.98 KB | None | 0 0
  1. package com.doneit.emiltonia.ui.who.graph
  2.  
  3. import android.graphics.*
  4. import android.os.Build
  5. import android.os.Bundle
  6. import android.support.annotation.RequiresApi
  7. import android.util.Log
  8. import android.view.Gravity
  9. import android.view.MotionEvent
  10. import android.view.WindowManager
  11. import android.widget.Toast
  12.  
  13. import com.doneit.emiltonia.R
  14. import com.doneit.emiltonia.data.entity.BabyEntity
  15. import com.doneit.emiltonia.data.entity.PercentileEntity
  16. import com.doneit.emiltonia.data.entity.ScaleEntity
  17. import com.doneit.emiltonia.ui.base.BaseContract
  18. import com.doneit.emiltonia.ui.base.inject.BaseInjectActivity
  19. import com.github.mikephil.charting.charts.LineChart
  20. import com.github.mikephil.charting.components.*
  21. import com.github.mikephil.charting.data.Entry
  22. import com.github.mikephil.charting.data.LineData
  23. import com.github.mikephil.charting.data.LineDataSet
  24. import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
  25. import com.github.mikephil.charting.highlight.Highlight
  26. import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
  27. import com.github.mikephil.charting.listener.ChartTouchListener
  28. import com.github.mikephil.charting.listener.OnChartGestureListener
  29. import com.github.mikephil.charting.listener.OnChartValueSelectedListener
  30. import com.github.mikephil.charting.renderer.XAxisRenderer
  31. import com.github.mikephil.charting.renderer.YAxisRenderer
  32. import com.github.mikephil.charting.utils.MPPointF
  33. import com.github.mikephil.charting.utils.Transformer
  34. import com.github.mikephil.charting.utils.Utils
  35. import com.github.mikephil.charting.utils.ViewPortHandler
  36. import kotlinx.android.synthetic.main.activity_who_graph.*
  37. import timber.log.Timber
  38. import java.util.*
  39.  
  40. import javax.inject.Inject
  41.  
  42. class WhoGraphNewActivity : BaseInjectActivity(), WhoGraphContract.View,
  43.         OnChartGestureListener, OnChartValueSelectedListener {
  44.  
  45.     public var mChart: LineChart? = null
  46.  
  47.     private var dataSets = ArrayList<ILineDataSet>()
  48.  
  49.     companion object {
  50.         private const val KEY_EXTRA_BABY_ID = "KEY_EXTRA_BABY_ID"
  51.         private const val DAYS_IN_WEEK = 7
  52.     }
  53.  
  54.     @Inject
  55.     lateinit var presenter: WhoGraphPresenter
  56.  
  57.     private var babyId: Int = 0
  58.  
  59.     private var age = 0
  60.     private var baby: BabyEntity? = null
  61.  
  62.     private var percentileP3: MutableList<Double> = arrayListOf()
  63.     private var percentileP15: MutableList<Double> = arrayListOf()
  64.     private var percentileP50: MutableList<Double> = arrayListOf()
  65.     private var percentileP85: MutableList<Double> = arrayListOf()
  66.     private var percentileP97: MutableList<Double> = arrayListOf()
  67.  
  68.     private var percentileBabyScales: MutableList<Double> = arrayListOf()
  69.  
  70.     override fun getPresenter(): BaseContract.Presenter<*>? {
  71.         return presenter
  72.     }
  73.  
  74.     override fun showBabyInfo(babyEntity: BabyEntity) {
  75.         baby = babyEntity
  76.         age = baby?.age!! / DAYS_IN_WEEK
  77.         age = 26
  78.     }
  79.  
  80.     override fun showPercentilesList(list: List<PercentileEntity>) {
  81. //        Toast.makeText(this@WhoGraphNewActivity, "percentiles ${list.size}", Toast.LENGTH_SHORT).show()
  82.         list.forEach {
  83.             percentileP3.add(it.p3.toDouble()*1000)
  84.             percentileP15.add(it.p15.toDouble()*1000)
  85.             Timber.e("P15 = ${it.p15}")
  86.             percentileP50.add(it.p50.toDouble()*1000)
  87.             percentileP85.add(it.p85.toDouble()*1000)
  88.             percentileP97.add(it.p97.toDouble()*1000)
  89.         }
  90.         Timber.d("P3 ${percentileP3.size}")
  91.         Timber.d("P15 ${percentileP15.size}")
  92.         Timber.d("P50 ${percentileP50.size}")
  93.         Timber.d("P85 ${percentileP85.size}")
  94.         Timber.d("P97 ${percentileP97.size}")
  95.     }
  96.  
  97.     @RequiresApi(Build.VERSION_CODES.O)
  98.     override fun showScalesList(list: List<ScaleEntity>) {
  99.         Toast.makeText(this@WhoGraphNewActivity, "baby scales ${list.size}", Toast.LENGTH_SHORT).show()
  100.         list.forEach {
  101.             Timber.e("ttttt = ${it.weight}")
  102.             percentileBabyScales.add(it.weight.toDouble()*1000)
  103.         }
  104.         Timber.d("percentileBabyScales ${percentileBabyScales.size}")
  105.  
  106.         Collections.sort(percentileBabyScales)
  107.  
  108. //        createSimpleGraph()
  109.         setupChart()
  110.         setupBabyLine()
  111.     }
  112.  
  113.     private fun createSimpleGraph() {
  114.         setData(percentileP3)
  115.         setDataP3()
  116.         setDataP15()
  117.         setDataP50()
  118.         setDataP85()
  119.         setDataP97()
  120.         val data = LineData(dataSets)
  121.         mChart!!.data = data
  122.     }
  123.  
  124.  
  125.  
  126.     @RequiresApi(Build.VERSION_CODES.O)
  127.     override fun onCreate(savedInstanceState: Bundle?) {
  128.         super.onCreate(savedInstanceState)
  129.         setContentView(R.layout.activity_who_graph_new)
  130.  
  131.         setSupportActionBar(toolbar)
  132.         supportActionBar?.setDisplayShowTitleEnabled(false)
  133.  
  134.         toolbarTitle.setText(R.string.who_graph_title)
  135.         toolbar.setNavigationOnClickListener { onBackPressed() }
  136.         toolbar.setNavigationIcon(R.drawable.ic_back)
  137.  
  138.         babyId = intent.getIntExtra(WhoGraphNewActivity.KEY_EXTRA_BABY_ID, 0)
  139.  
  140.         presentationComponent.inject(this)
  141.         presenter.attachToView(this)
  142.  
  143.  
  144. //        presenter.getAllPercentilesByBabyId(babyId)
  145.         presenter.getBabyInfo(babyId)
  146.  
  147.  
  148.  
  149.  
  150.  
  151.  
  152.  
  153.         mChart = findViewById(R.id.chart1)
  154.         mChart!!.onChartGestureListener = this
  155.         mChart!!.setOnChartValueSelectedListener(this)
  156.         mChart!!.setDrawGridBackground(false)
  157.  
  158.         // no description text
  159.         mChart!!.description.isEnabled = false
  160.  
  161.         // enable touch gestures
  162.         mChart!!.setTouchEnabled(true)
  163.  
  164.         // enable scaling and dragging
  165.         mChart!!.isDragEnabled = true
  166.         mChart!!.setScaleEnabled(true)
  167.         // mChart.setScaleXEnabled(true);
  168.         // mChart.setScaleYEnabled(true);
  169.  
  170.         // if disabled, scaling can be done on x- and y-axis separately
  171.         mChart!!.setPinchZoom(true)
  172.  
  173.         // set an alternative background color
  174.         // mChart.setBackgroundColor(Color.GRAY);
  175.  
  176.         // create a custom MarkerView (extend MarkerView) and specify the layout
  177.         // to use for it
  178. //        val mv = MyMarkerView(this, R.layout.custom_marker_view)
  179. //        mv.setChartView(mChart) // For bounds control
  180. //        mChart!!.marker = mv // Set the marker to the chart
  181.  
  182.         // x-axis limit line
  183.         val llXAxis = LimitLine(10f, "Index 10")
  184.         llXAxis.lineWidth = 4f
  185.         llXAxis.enableDashedLine(10f, 10f, 0f)
  186.         llXAxis.labelPosition = LimitLine.LimitLabelPosition.RIGHT_BOTTOM
  187.         llXAxis.textSize = 10f
  188.  
  189.         val xAxis = mChart!!.xAxis
  190.         xAxis.enableGridDashedLine(10f, 10f, 0f)
  191.         //xAxis.setValueFormatter(new MyCustomXAxisValueFormatter());
  192.         //xAxis.addLimitLine(llXAxis); // add x-axis limit line
  193.  
  194.  
  195.         val leftAxis = mChart!!.axisLeft
  196.         leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
  197.         leftAxis.removeAllLimitLines() // reset all limit lines to avoid overlapping lines
  198. //        leftAxis.addLimitLine(ll1)
  199. //        leftAxis.addLimitLine(ll2)
  200.         leftAxis.axisMaximum = 10f
  201.         leftAxis.axisMinimum = 0f
  202. //        leftAxis.yOffset = 20f;
  203.         leftAxis.enableGridDashedLine(30f, 10f, 0f)
  204.         leftAxis.setDrawZeroLine(false)
  205.  
  206.         // limit lines are drawn behind data (and not on top)
  207.         leftAxis.setDrawLimitLinesBehindData(true)
  208.  
  209.         val yLabel = ArrayList<String>()
  210.         for (i in 0..10) {
  211.             yLabel.add(i.toString().plus(" 000 g"))
  212.         }
  213.  
  214.         leftAxis.setValueFormatter { value, axis ->
  215.             return@setValueFormatter yLabel[value.toInt()]
  216.         }
  217.  
  218.         mChart!!.axisRight.isEnabled = false
  219.  
  220.         /*val xLabel = ArrayList<String>()
  221.         for (i in 0..age) {
  222.             var weekString = ""
  223. //            if (i == 0) weekString = "Birthday"
  224.             if (i == 1) weekString = "week"
  225.             else weekString = "weeks"
  226.             xLabel.add(i.toString().plus(" ").plus(weekString))
  227.         }*/
  228.  
  229.         val xAxis2 = mChart!!.xAxis
  230.         xAxis2.position = XAxis.XAxisPosition.BOTTOM
  231.         xAxis2.setDrawGridLines(true)
  232.         xAxis2.gridColor = Color.LTGRAY
  233. //        xAxis2.gridColor = Color.rgb(241,241,241)
  234.         xAxis2.enableGridDashedLine(30f, 0f, 0f)
  235.         /*xAxis2.setValueFormatter { value, axis ->
  236.             return@setValueFormatter xLabel[value.toInt()]
  237.         }*/
  238.  
  239.         val left = mChart!!.axisLeft
  240.         left.setDrawGridLines(true)
  241.         left.gridColor = Color.LTGRAY
  242.         left.enableGridDashedLine(30f, 0f, 0f)
  243.  
  244.  
  245.         //mChart.getViewPortHandler().setMaximumScaleY(2f);
  246.         //mChart.getViewPortHandler().setMaximumScaleX(2f);
  247.  
  248.         // add data
  249. //        setData(45, 2f)
  250.  
  251.         //        mChart.setVisibleXRange(20);
  252.         //        mChart.setVisibleYRange(20f, AxisDependency.LEFT);
  253.         //        mChart.centerViewTo(20, 50, AxisDependency.LEFT);
  254.  
  255. //        mChart!!.animateX(2500)
  256.         //mChart.invalidate();
  257.  
  258.         // get the legend (only possible after setting data)
  259.         val l = mChart!!.legend
  260.  
  261.         // modify the legend ...
  262.         l.form = Legend.LegendForm.LINE
  263. //        l.setDrawInside(true)
  264.  
  265. //        l.addDashedLine(width: dashWidth, pattern: dashes[0], color: statisticColor)
  266.  
  267.  
  268.         // // dont forget to refresh the drawing
  269. //         mChart!!.invalidate();
  270.  
  271.         /*setupChart()
  272.         setupBabyLine()*/
  273.     }
  274.  
  275.  
  276.  
  277.     @RequiresApi(Build.VERSION_CODES.O)
  278.     fun setupChart() {
  279.  
  280.         mChart!!.setBackgroundColor(Color.rgb(0.97f, 0.97f, 0.97f))
  281.  
  282.         val lineChartView = mChart!!
  283. //        let lineChartView = self.chartView.lineChartView!
  284.         lineChartView.setBackgroundColor(Color.rgb(0.97f, 0.97f, 0.97f))/* = chartBackgroundColor*/
  285.         lineChartView.setBorderColor(Color.rgb(0.60f, 0.60f, 0.60f))/* = chartBorderColor*/
  286.         //lineChartView.borderLineWidth = 1
  287.         lineChartView.setDrawBorders(true)
  288. //        lineChartView.dragXEnabled = true
  289. //        lineChartView.dragYEnabled = true//false
  290. //        lineChartView.scaleXEnabled = true
  291. //        lineChartView.scaleYEnabled = true//false
  292.         lineChartView.viewPortHandler.setMaximumScaleX(4f)
  293.         lineChartView.viewPortHandler.setMaximumScaleY(2f)
  294. //        lineChartView.delegate = self
  295.  
  296.         var xValueRenderer = XValueRenderer(
  297.                 lineChartView.viewPortHandler,
  298.                 lineChartView.xAxis,
  299.                 lineChartView.rendererXAxis.transformer
  300.         )
  301. //        val baby = self.dataProvider.baby
  302. //        xValueRenderer.birthColor = Color.GREEN   // = self.babyChartColor(baby).first!
  303.         lineChartView.setXAxisRenderer(xValueRenderer)
  304.  
  305.         val xAxis = lineChartView.xAxis
  306.         xAxis.position = XAxis.XAxisPosition.BOTTOM
  307. //        xAxis.gridColor = Color.rgb(0.8f, 0.8f, 0.8f)
  308. //        xAxis.labelFont = labelFont
  309.         xAxis.textColor = Color.LTGRAY
  310.         xAxis.valueFormatter = XValueFormatter()
  311. //        xAxis.labelCount = UIScreen.main.bounds.size.width > 375 ? 5 : 4
  312.         xAxis.labelCount = /*5*/4
  313.         xAxis.textColor = Color.BLACK
  314.         //todo find out how manipulate with limits
  315. //        xAxis.axisMinimum = 0f/*self.dataProvider.leftXLimit*/
  316. //        xAxis.axisMaximum = 0f/*self.dataProvider.rightXLimit*/
  317.  
  318. //        lineChartView.getAxis(.right).enabled = false
  319. //        lineChartView.getAxis(YAxis.AxisDependency.RIGHT).
  320.  
  321.         /*val yValueRenderer = YValueRenderer(
  322.                 lineChartView.viewPortHandler,
  323.         lineChartView.getAxis(YAxis.AxisDependency.LEFT),
  324.         lineChartView.rendererXAxis.transformer
  325.         )
  326.         lineChartView.rendererLeftYAxis = yValueRenderer*/
  327.  
  328.         var yAxis = lineChartView.getAxis(YAxis.AxisDependency.LEFT)
  329.         yAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART)
  330.                 yAxis.setDrawTopYLabelEntry(false)//drawTopYLabelEntryEnabled = false
  331.         yAxis.setDrawLimitLinesBehindData(false)//drawBottomYLabelEntryEnabled = false
  332.         yAxis.axisMinimum = 0f/*self.dataProvider.lowerYLimit*/
  333.         yAxis.axisMaximum = 10000f/*self.dataProvider.upperYLimit*/
  334. //        yAxis.labelCount = Int((yAxis.axisMaximum - yAxis.axisMinimum) / self.dataProvider.yStep)
  335.         yAxis.labelCount = ((yAxis.axisMaximum - yAxis.axisMinimum).toInt()) / 1000
  336. //        yAxis.gridColor = Color.rgb(0.8f,0.8f,0.8f)
  337. //        yAxis.labelFont = labelFont
  338.         yAxis.textColor = Color.BLACK
  339.         yAxis.valueFormatter = YValueFormatter()
  340.         yAxis.xOffset = yAxis.xOffset + 4f/*yLabelRectInset*/
  341.     }
  342.  
  343.  
  344.     /*fun chartScaled(_ chartView: ChartViewBase, scaleX: Float, scaleY: Float) {
  345.         recalculateXLimits()
  346.     }
  347.  
  348.     fun chartTranslated(_ chartView: ChartViewBase, dX: Float, dY: Float) {
  349.         recalculateXLimits()
  350.     }*/
  351.  
  352.  
  353.  
  354.  
  355.     fun setupBabyLine() {
  356.  
  357. //        val baby = self.dataProvider.baby
  358.  
  359.         val values2 = ArrayList<Entry>()
  360.  
  361. //        val age = percentileBabyScales[0]
  362. //        val age = 20
  363.         Timber.e("AGEee = $age")
  364.         for (i in 0 until /*percentileBabyScales.size*/age) {
  365.             val value = (Math.random() * 9000).toFloat() + 13
  366. //            Timber.e("value = $value")
  367.             Timber.e("baby value = ${percentileBabyScales[i].toFloat()}")
  368. //            values2.add(Entry(i.toFloat(), /*percentileP3*/percentileBabyScales[i].toFloat()/*value*/, resources.getDrawable(R.drawable.star)))
  369.             values2.add(Entry(i.toFloat(), percentileBabyScales[i].toFloat()))
  370.         }
  371.  
  372.  
  373.  
  374.         /*val set2 = LineDataSet(values2, "P3")
  375.  
  376.         set2.setDrawIcons(false)
  377.  
  378.         // set the line to be drawn like this "- - - - - -"
  379.         set2.enableDashedLine(10f, 5f, 0f)
  380.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  381.         set2.color = Color.MAGENTA
  382.         set2.setCircleColor(Color.MAGENTA)
  383.         set2.lineWidth = 1f
  384.         set2.circleRadius = 2f
  385.         set2.setDrawCircles(false)
  386.         set2.setDrawCircleHole(false)
  387.         set2.setDrawValues(false)
  388.         set2.setDrawFilled(false)
  389.         set2.formLineWidth = 1f
  390.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  391.         set2.formSize = 15f*/
  392.  
  393.  
  394. //        val line = LineDataSet(values: self.dataProvider.babyDataEntry, "Vasya")
  395.         val line = LineDataSet(values2, baby?.name)
  396.  
  397.         line.setDrawIcons(false)
  398.  
  399.         // set the line to be drawn like this "- - - - - -"
  400.         line.enableDashedLine(10f, 5f, 0f)
  401.         line.enableDashedHighlightLine(10f, 5f, 0f)
  402.  
  403.  
  404.         line.color = Color.rgb(152,210,212)
  405.         line.setCircleColor(Color.rgb(152,210,212))
  406. //        line.setCircleColorHole(line.colors[0])
  407.         line.lineWidth = 3f/*babyLineWidth*/
  408.         line.circleRadius = /*line.lineWidth*/5f /** 3*/
  409.         line.circleHoleRadius = line.circleRadius * 0.8f
  410.         line.axisDependency = YAxis.AxisDependency.LEFT
  411.         line.setDrawValues(true)
  412. //        line.valueTextSize = 10f
  413.         line.setDrawVerticalHighlightIndicator(false)
  414.         line.setDrawHorizontalHighlightIndicator(false)
  415.  
  416.         line.formLineWidth = 1f
  417.         line.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  418.         line.formSize = 15f
  419.  
  420. //        val data = LineChartData()
  421. //        statisticLines().forEach {
  422. //            data.addDataSet($0)
  423. //        }
  424.  
  425.         val data = LineData()
  426.  
  427.         data.addDataSet(line)
  428.         data.addDataSet(setDataP3())
  429.         data.addDataSet(setDataP15())
  430.         data.addDataSet(setDataP50())
  431.         data.addDataSet(setDataP85())
  432.         data.addDataSet(setDataP97())
  433.  
  434.         mChart!!.data = data
  435.         mChart!!.description = null
  436.         mChart!!.invalidate()
  437.     }
  438.  
  439.  
  440.     class YValueRenderer(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, trans: Transformer?) : YAxisRenderer(viewPortHandler, yAxis, trans) {
  441.  
  442.  
  443.         override fun renderAxisLabels(context: Canvas) {
  444.  
  445.             /*guard let yAxis = self.axis as? YAxis else {
  446.                 return
  447.             }
  448.             if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled {
  449.                 return
  450.             }*/
  451.             val yAxis = mYAxis
  452.             if (yAxis == null) return
  453.  
  454.             if (yAxis.isEnabled || !yAxis.isDrawLabelsEnabled) return
  455.  
  456.  
  457.             val xoffset = yAxis.xOffset
  458. //            val yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset
  459.             val yoffset = Utils.calcTextHeight(mAxisLabelPaint, "A") / 2.5 + yAxis.yOffset
  460.             val dependency = yAxis.axisDependency
  461.             val labelPosition = yAxis.labelPosition
  462.  
  463.             var xPos = 0f/*CGFloat(0.0)*/
  464.             val textAlign = mAxisLabelPaint /*NSTextAlignment*///YAxis.AxisDependency
  465.  
  466.             if (dependency == YAxis.AxisDependency.LEFT) {
  467.                 if (labelPosition == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
  468. //                    textAlign = YAxis.AxisDependency.RIGHT
  469.                     textAlign.textAlign = Paint.Align.RIGHT
  470.                     xPos = mViewPortHandler.offsetLeft() - xoffset
  471.                 } else {
  472. //                    textAlign = YAxis.AxisDependency.LEFT
  473.                     textAlign.textAlign = Paint.Align.LEFT
  474.                     xPos = mViewPortHandler.offsetLeft() + xoffset
  475.                 }
  476.             } else {
  477.                 if (labelPosition == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
  478. //                    textAlign = YAxis.AxisDependency.LEFT
  479.                     textAlign.textAlign = Paint.Align.LEFT
  480.                     xPos = mViewPortHandler.contentRight() + xoffset
  481.                 } else {
  482. //                    textAlign = YAxis.AxisDependency.RIGHT
  483.                     textAlign.textAlign = Paint.Align.RIGHT
  484.                     xPos = mViewPortHandler.contentRight() - xoffset
  485.                 }
  486.             }
  487.  
  488.             val fixedPosition = xPos
  489.             val positions = transformedPositions
  490. //            val offset = yoffset - yAxis.labelFont.lineHeight
  491.             val offset = 0
  492.  
  493. //            var from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1
  494.             var from = -1
  495.             if (yAxis.isDrawBottomYLabelEntryEnabled) from = 0
  496.             else from = 1
  497.             var to = -1
  498.             if (yAxis.isDrawTopYLabelEntryEnabled) to = yAxis.mEntryCount
  499.             else to = yAxis.mEntryCount - 1
  500. //            val to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1)
  501. //            val attributes = [NSAttributedStringKey.font: labelFont]
  502.             val col = /*yLabelBackgroundColor*/Color.LTGRAY
  503.  
  504.             for (i in from..to step 1) {
  505. //                    for i in stride(from: from, to: to, by: 1) {
  506.  
  507.                 val text = yAxis.getFormattedLabel(i)
  508.                 var point = /*CGPoint*/MPPointF(fixedPosition, positions[i] + offset)
  509. //                val textSize = text.size(withAttributes: attributes)
  510. //                val textSize = text.length
  511. //                val textSize = textAlign.textSize
  512.                 val textSize = text.length
  513.  
  514.                 if (textAlign == Paint.Align.CENTER) {
  515.                     point.x -= textSize/*.width*/ / 2.0f
  516.                 } else if (textAlign == YAxis.AxisDependency.RIGHT) {
  517.                     point.x -= textSize/*.width*/
  518.                 }
  519.  
  520.                 val rect = RectF(point.x, point.y, 4f, 0f)
  521.                 val path = Path()
  522.                 path.addRect(rect, Path.Direction.CW)
  523.  
  524.                 path.rewind()
  525.  
  526.  
  527. //                UIGraphicsPushContext(context)
  528. //                col.set()
  529. //                path.fill()
  530. //                UIGraphicsPopContext()
  531.  
  532.                 /*val rect = CGRect(point, textSize).insetBy(-yLabelRectInset, 0)
  533.                 val path = UIBezierPath.init(rect, yLabelRectInset)
  534.  
  535.                 UIGraphicsPushContext(context)
  536.                 col.set()
  537.                 path.fill()
  538.                 UIGraphicsPopContext()*/
  539.             }
  540.  
  541.             super.renderAxisLabels(context)
  542.         }
  543.     }
  544.  
  545.     class XValueRenderer(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, trans: Transformer?) : XAxisRenderer(viewPortHandler, xAxis, trans) {
  546.  
  547.         val birthStr = "Birthday"/*CommonStrings.Units.birthday.localized*/
  548.         val birthImgSize = 15f/*CGFloat(15)*/
  549.  
  550.  
  551. //        val birthImg = R.drawable.star
  552. //        birthImg
  553.  
  554. //        private(set) var birthImg:UIImage? = nil
  555.  
  556. //        var birthColor: UIColor? = nil {
  557. //            didSet {
  558. //                if let col = birthColor, let img = UIImage(named: "birth_image") {
  559. //                birthImg = img.imageWithColor(color: col)
  560. //            } else {
  561. //                birthImg = nil
  562. //            }
  563. //            }
  564. //        }
  565.  
  566.         override fun drawLabel(context: Canvas, formattedLabel: String, x: Float, y: Float, anchor: MPPointF, angleRadians: Float) {
  567.  
  568.             if (formattedLabel == "kBirthday") {
  569.  
  570.                 Timber.e("drawLabel formattedLabel == kBirthday")
  571.  
  572. //                var mAttributes = attributes
  573. //
  574. //                if let col = birthColor {
  575. //                    mAttributes[NSAttributedStringKey.foregroundColor] = col
  576. //                }
  577. //                if let font = mAttributes[NSAttributedStringKey.font] as? UIFont {
  578. //                    let name = font.fontName.replacingOccurrences(of: "Regular", with: "SemiBold")
  579. //                    mAttributes[NSAttributedStringKey.font] = UIFont(name: name, size: font.pointSize) ?? font
  580. //                }
  581. //
  582. //                if let img = birthImg {
  583. //                    UIGraphicsPushContext(context)
  584. //                    img.draw(in: CGRect(x: x - birthImgSize/2, y: viewPortHandler.contentBottom - birthImgSize/2, width: birthImgSize, height: birthImgSize))
  585. //                    UIGraphicsPopContext()
  586. //                }
  587.  
  588.                 super.drawLabel(context, formattedLabel, x, y, anchor, angleRadians)
  589.                 return
  590.             }
  591.             super.drawLabel(context, formattedLabel, x, y, anchor, angleRadians)
  592.         }
  593.     }
  594.  
  595.  
  596.     class XValueFormatter: IndexAxisValueFormatter() {
  597.  
  598.         override fun getFormattedValue(value: Float, axis: AxisBase?): String {
  599.             if (value == 0f)
  600.                 return "kBirthday"
  601.             if (value < 1)
  602.                 return ""
  603.             val i = value.toInt()
  604.             return i.toString().plus(" weeks")
  605. //            return value.toString()
  606.         }
  607.     }
  608.  
  609.     class YValueFormatter: IndexAxisValueFormatter() {
  610.  
  611.         override fun getFormattedValue(value: Float, axis: AxisBase?): String {
  612.             var s = value.toInt().toString()
  613. //            if (s.count() > 3) {
  614. //                s.plus(" 000 g")
  615. //            }
  616.             s = s.plus(" g")
  617.             var stroke = ""
  618.             if (value != 0f) {
  619.                 stroke = s.substring(0, 1).plus(".").plus(s.substring(1, s.length))
  620.             }
  621.             else {
  622.                 stroke = s.substring(0,1).plus(s.substring(1, s.length))
  623.             }
  624. //            return s.plus(" g")
  625.             return stroke
  626.         }
  627.     }
  628.  
  629.  
  630.  
  631.  
  632.  
  633.  
  634.  
  635.  
  636.  
  637.  
  638.  
  639.  
  640.  
  641.     private fun setDataP3() : LineDataSet {
  642.         val values2 = ArrayList<Entry>()
  643.  
  644. //        val age = percentileBabyScales[0]
  645. //        val age = 20
  646.         for (i in 0 until /*percentileBabyScales.size*/age) {
  647. //            val value = (Math.random() * range).toFloat() + 13
  648.             values2.add(Entry(i.toFloat(), percentileP3[i].toFloat(), resources.getDrawable(R.drawable.star)))
  649.         }
  650.  
  651.         val set2 = LineDataSet(values2, "P3")
  652.         set2.setDrawIcons(false)
  653.  
  654.         // set the line to be drawn like this "- - - - - -"
  655.         set2.enableDashedLine(10f, 5f, 0f)
  656.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  657.         set2.color = Color.LTGRAY
  658.         set2.setCircleColor(Color.LTGRAY)
  659.         set2.lineWidth = 1f
  660.         set2.circleRadius = 2f
  661.         set2.setDrawCircles(false)
  662.         set2.setDrawCircleHole(false)
  663.         set2.setDrawValues(false)
  664.         set2.setDrawFilled(false)
  665.         set2.formLineWidth = 1f
  666.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  667.         set2.formSize = 15f
  668.  
  669. //        dataSets.add(set2) // add the datasets
  670.         return  set2
  671.     }
  672.  
  673.     private fun setDataP15() : LineDataSet {
  674.         val values2 = ArrayList<Entry>()
  675.  
  676.         for (i in 0 until age) {
  677.             values2.add(Entry(i.toFloat(), percentileP15[i].toFloat(), resources.getDrawable(R.drawable.star)))
  678.         }
  679.  
  680.         val set2 = LineDataSet(values2, "P15")
  681.         set2.setDrawIcons(false)
  682.  
  683.         // set the line to be drawn like this "- - - - - -"
  684.         set2.enableDashedLine(10f, 5f, 0f)
  685.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  686.         set2.color = Color.GRAY
  687.         set2.setCircleColor(Color.GRAY)
  688.         set2.lineWidth = 1f
  689.         set2.circleRadius = 2f
  690.         set2.setDrawCircles(false)
  691.         set2.setDrawCircleHole(false)
  692.         set2.setDrawValues(false)
  693.         set2.setDrawFilled(false)
  694.         set2.formLineWidth = 1f
  695.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  696.         set2.formSize = 15f
  697.  
  698. //        dataSets.add(set2) // add the datasets
  699.         return set2
  700.     }
  701.  
  702.     private fun setDataP50() : LineDataSet {
  703.         val values2 = ArrayList<Entry>()
  704.  
  705.         for (i in 0 until age) {
  706.             values2.add(Entry(i.toFloat(), percentileP50[i].toFloat(), resources.getDrawable(R.drawable.star)))
  707.         }
  708.  
  709.         val set2 = LineDataSet(values2, "P50")
  710.         set2.setDrawIcons(false)
  711.  
  712.         // set the line to be drawn like this "- - - - - -"
  713.         set2.enableDashedLine(10f, 5f, 0f)
  714.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  715.         set2.color = Color.DKGRAY
  716.         set2.setCircleColor(Color.DKGRAY)
  717.         set2.lineWidth = 1f
  718.         set2.circleRadius = 2f
  719.         set2.setDrawCircles(false)
  720.         set2.setDrawCircleHole(false)
  721.         set2.setDrawValues(false)
  722.         set2.setDrawFilled(false)
  723.         set2.formLineWidth = 1f
  724.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  725.         set2.formSize = 15f
  726.  
  727. //        dataSets.add(set2) // add the datasets
  728.         return set2
  729.     }
  730.  
  731.     private fun setDataP85() : LineDataSet {
  732.         val values2 = ArrayList<Entry>()
  733.  
  734.         for (i in 0 until age) {
  735.             values2.add(Entry(i.toFloat(), percentileP85[i].toFloat(), resources.getDrawable(R.drawable.star)))
  736.         }
  737.  
  738.         val set2 = LineDataSet(values2, "P85")
  739.         set2.setDrawIcons(false)
  740.  
  741.         // set the line to be drawn like this "- - - - - -"
  742.         set2.enableDashedLine(10f, 5f, 0f)
  743.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  744.         set2.color = Color.LTGRAY
  745.         set2.setCircleColor(Color.LTGRAY)
  746.         set2.lineWidth = 1f
  747.         set2.circleRadius = 2f
  748.         set2.setDrawCircles(false)
  749.         set2.setDrawCircleHole(false)
  750.         set2.setDrawValues(false)
  751.         set2.setDrawFilled(false)
  752.         set2.formLineWidth = 1f
  753.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  754.         set2.formSize = 15f
  755.  
  756. //        dataSets.add(set2) // add the datasets
  757.         return set2
  758.     }
  759.  
  760.     private fun setDataP97() : LineDataSet {
  761.         val values2 = ArrayList<Entry>()
  762.  
  763.         for (i in 0 until age) {
  764.             values2.add(Entry(i.toFloat(), percentileP97[i].toFloat(), resources.getDrawable(R.drawable.star)))
  765.         }
  766.  
  767.         val set2 = LineDataSet(values2, "P97")
  768.         set2.setDrawIcons(false)
  769.  
  770.         // set the line to be drawn like this "- - - - - -"
  771.         set2.enableDashedLine(10f, 5f, 0f)
  772.         set2.enableDashedHighlightLine(10f, 5f, 0f)
  773.         set2.color = Color.LTGRAY
  774.         set2.setCircleColor(Color.LTGRAY)
  775.         set2.lineWidth = 1f
  776.         set2.circleRadius = 2f
  777.         set2.setDrawCircles(false)
  778.         set2.setDrawCircleHole(false)
  779.         set2.setDrawValues(false)
  780.         set2.setDrawFilled(false)
  781.         set2.formLineWidth = 1f
  782.         set2.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  783.         set2.formSize = 15f
  784.  
  785. //        dataSets.add(set2) // add the datasets
  786.         return set2
  787.     }
  788.  
  789.  
  790.  
  791.     private fun setData(list: MutableList<Double>) {
  792.  
  793.         Timber.e("setData count = ${list.size}")
  794.  
  795.         val values = ArrayList<Entry>()
  796.  
  797.         for (i in 0 until age) {
  798.             values.add(Entry(i.toFloat(), percentileBabyScales[i].toFloat(), resources.getDrawable(R.drawable.star)))
  799.         }
  800.  
  801.         val set1: LineDataSet
  802.  
  803.         if (mChart!!.data != null && mChart!!.data.dataSetCount > 0) {
  804.             set1 = mChart!!.data.getDataSetByIndex(0) as LineDataSet
  805.             set1.values = values
  806.             mChart!!.data.notifyDataChanged()
  807.             mChart!!.notifyDataSetChanged()
  808.         } else {
  809.             set1 = LineDataSet(values, "Baby Name")
  810.             set1.setDrawIcons(false)
  811.  
  812.             // set the line to be drawn like this "- - - - - -"
  813.             set1.enableDashedLine(10f, 5f, 0f)
  814.             set1.enableDashedHighlightLine(10f, 5f, 0f)
  815.             set1.color = Color.BLACK
  816.             set1.setCircleColor(Color.BLACK)
  817.             set1.lineWidth = 1f
  818.             set1.circleRadius = 3f
  819. //            set1.setDrawCircles(true)
  820.             set1.setDrawCircleHole(false)
  821.             set1.setDrawValues(false)
  822.             set1.setDrawFilled(false)
  823.             set1.formLineWidth = 1f
  824.             set1.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  825.             set1.formSize = 5f
  826.             /*set1.lineWidth = 1f
  827.             set1.circleRadius = 3f
  828.             set1.setDrawCircleHole(false)
  829.             set1.valueTextSize = 9f
  830.             set1.setDrawFilled(true)
  831.             set1.formLineWidth = 1f
  832.             set1.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
  833.             set1.formSize = 15f*/
  834.  
  835.  
  836. //            dataSets.add(set1)
  837.         }
  838.         mChart!!.invalidate()
  839.     }
  840.  
  841.  
  842.  
  843.     override fun onChartGestureStart(me: MotionEvent, lastPerformedGesture: ChartTouchListener.ChartGesture) {
  844.         Log.i("Gesture", "START, x: " + me.x + ", y: " + me.y)
  845.     }
  846.  
  847.     override fun onChartGestureEnd(me: MotionEvent, lastPerformedGesture: ChartTouchListener.ChartGesture) {
  848.         Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture)
  849.  
  850.         // un-highlight values after the gesture is finished and no single-tap
  851.         if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
  852.             mChart!!.highlightValues(null) // or highlightTouch(null) for callback to onNothingSelected(...)
  853.     }
  854.  
  855.     override fun onChartLongPressed(me: MotionEvent) {
  856.         Log.i("LongPress", "Chart longpressed.")
  857.     }
  858.  
  859.     override fun onChartDoubleTapped(me: MotionEvent) {
  860.         Log.i("DoubleTap", "Chart double-tapped.")
  861.     }
  862.  
  863.     override  fun onChartSingleTapped(me: MotionEvent) {
  864.         Log.i("SingleTap", "Chart single-tapped.")
  865.     }
  866.  
  867.     override  fun onChartFling(me1: MotionEvent, me2: MotionEvent, velocityX: Float, velocityY: Float) {
  868.         Log.i("Fling", "Chart flinged. VeloX: $velocityX, VeloY: $velocityY")
  869.     }
  870.  
  871.     override   fun onChartScale(me: MotionEvent, scaleX: Float, scaleY: Float) {
  872.         Log.i("Scale / Zoom", "ScaleX: $scaleX, ScaleY: $scaleY")
  873.         recalculateXLimits()
  874.     }
  875.  
  876.     override  fun onChartTranslate(me: MotionEvent, dX: Float, dY: Float) {
  877.         Log.i("Translate / Move", "dX: $dX, dY: $dY")
  878.         recalculateXLimits()
  879.     }
  880.  
  881.     fun recalculateXLimits() {
  882.  
  883.         val lineChartView = mChart!!
  884. //        val minX = -Double(4.0 / lineChartView.scaleX)
  885.         val minX = -4.0/mChart!!.scaleX
  886.  
  887.         if (lineChartView.lowestVisibleX < minX) {
  888.             lineChartView.moveViewToX(minX.toFloat())
  889. //            lineChartView.setNeedsDisplay()
  890.             lineChartView.invalidate()
  891.         }
  892.     }
  893.  
  894.     override  fun onValueSelected(e: Entry, h: Highlight) {
  895.         Log.i("Entry selected", e.toString())
  896.         Log.i("LOWHIGH", "low: " + mChart!!.lowestVisibleX + ", high: " + mChart!!.highestVisibleX)
  897.         Log.i("MIN MAX", "xmin: " + mChart!!.xChartMin + ", xmax: " + mChart!!.xChartMax + ", ymin: " + mChart!!.yChartMin + ", ymax: " + mChart!!.yChartMax)
  898.     }
  899.  
  900.     override   fun onNothingSelected() {
  901.         Log.i("Nothing selected", "Nothing selected.")
  902.     }
  903. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement