Advertisement
andyshon

WhoGraphNewActivity-pre-v

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