Advertisement
andyshon

WhoGraphActivity - pre release sprint 3

Sep 28th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 31.05 KB | None | 0 0
  1. package com.doneit.emiltonia.ui.who.graph
  2.  
  3. import android.Manifest
  4. import android.content.Context
  5. import android.content.Intent
  6. import android.content.pm.PackageManager
  7. import android.graphics.*
  8. import android.graphics.drawable.Drawable
  9. import android.net.Uri
  10. import android.os.Build
  11. import android.os.Bundle
  12. import android.provider.MediaStore
  13. import android.support.annotation.RequiresApi
  14. import android.support.v4.app.ActivityCompat
  15. import android.text.SpannableStringBuilder
  16. import android.text.method.LinkMovementMethod
  17. import android.view.MotionEvent
  18. import android.view.View
  19. import android.widget.Toast
  20. import com.doneit.emiltonia.Const
  21.  
  22. import com.doneit.emiltonia.R
  23. import com.doneit.emiltonia.data.entity.PercentileEntity
  24. import com.doneit.emiltonia.data.entity.ScaleEntity
  25. import com.doneit.emiltonia.ui.base.BaseContract
  26. import com.doneit.emiltonia.ui.base.inject.BaseInjectActivity
  27. import com.doneit.emiltonia.utils.extensions.addClickableSpannable
  28. import com.doneit.emiltonia.utils.extensions.color
  29. import com.doneit.emiltonia.utils.extensions.drawable
  30. import com.doneit.emiltonia.utils.extensions.string
  31. import com.github.mikephil.charting.components.*
  32. import com.github.mikephil.charting.data.Entry
  33. import com.github.mikephil.charting.data.LineData
  34. import com.github.mikephil.charting.data.LineDataSet
  35. import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
  36. import com.github.mikephil.charting.listener.ChartTouchListener
  37. import com.github.mikephil.charting.listener.OnChartGestureListener
  38. import com.github.mikephil.charting.renderer.XAxisRenderer
  39. import com.github.mikephil.charting.renderer.YAxisRenderer
  40. import com.github.mikephil.charting.utils.MPPointF
  41. import com.github.mikephil.charting.utils.Transformer
  42. import com.github.mikephil.charting.utils.Utils
  43. import com.github.mikephil.charting.utils.ViewPortHandler
  44. import kotlinx.android.synthetic.main.activity_who_graph.*
  45. import timber.log.Timber
  46. import java.text.SimpleDateFormat
  47. import java.util.*
  48.  
  49. import javax.inject.Inject
  50.  
  51. class WhoGraphActivity : BaseInjectActivity(), WhoGraphContract.View,
  52.         OnChartGestureListener {
  53.    
  54.     companion object {
  55.         private const val KEY_EXTRA_IS_SHARED = "KEY_EXTRA_IS_SHARED"
  56.         private const val KEY_EXTRA_BABY_NAME = "KEY_EXTRA_BABY_NAME"
  57.         private const val KEY_EXTRA_BABY_AGE = "KEY_EXTRA_BABY_AGE"
  58.         private const val KEY_EXTRA_BABY_GENDER = "KEY_EXTRA_BABY_GENDER"
  59.         private const val KEY_EXTRA_BABY_WEIGHT = "KEY_EXTRA_BABY_WEIGHT"
  60.         private const val KEY_EXTRA_BABY_ID = "KEY_EXTRA_BABY_ID"
  61.         private const val DAYS_IN_WEEK = 7
  62.         private var babyGender = Const.Genders.MALE
  63.         private var babyWeight = 0f
  64.  
  65.         private var bitmap: Bitmap? = null
  66.         private var birthday = ""
  67.         private var weeks = ""
  68.         private var isDE = false
  69.     }
  70.  
  71.     @Inject
  72.     lateinit var presenter: WhoGraphPresenter
  73.  
  74.     private var babyId: Int = 0
  75.  
  76.     private var babyAge = 0
  77.     private var babyName = ""
  78.     private var scales = 0
  79.     private var isShared = false
  80.  
  81.     private val data = LineData()
  82.  
  83.     private var percentileP3: MutableList<Double> = arrayListOf()
  84.     private var percentileP15: MutableList<Double> = arrayListOf()
  85.     private var percentileP50: MutableList<Double> = arrayListOf()
  86.     private var percentileP85: MutableList<Double> = arrayListOf()
  87.     private var percentileP97: MutableList<Double> = arrayListOf()
  88.  
  89.     private val allPercentiles: MutableList<MutableList<Double>> = arrayListOf()
  90.     private val allDashedLinesLength: MutableList<Float> = arrayListOf(10f,10f,20f,10f,10f)
  91.     private val allDashedLinesSpaceLength: MutableList<Float> = arrayListOf(15f,10f,20f,10f,10f)
  92.  
  93.     private var percentileBabyScales: MutableList<Double> = arrayListOf()
  94.     private var percentileBabyScales2: MutableList<Double> = arrayListOf()
  95.  
  96.  
  97.     override fun getPresenter(): BaseContract.Presenter<*>? {
  98.         return presenter
  99.     }
  100.  
  101.     override fun showPercentilesList(list: List<PercentileEntity>) {
  102.         list.forEach {
  103.             percentileP3.add(it.p3.toDouble())
  104.             percentileP15.add(it.p15.toDouble())
  105.             percentileP50.add(it.p50.toDouble())
  106.             percentileP85.add(it.p85.toDouble())
  107.             percentileP97.add(it.p97.toDouble())
  108.         }
  109.         Timber.e("SIZE ${percentileP3.size} : ${percentileP3[0]} : ${percentileP15.size} : ${percentileP15[0]}")
  110.         allPercentiles.add(percentileP3)
  111.         allPercentiles.add(percentileP15)
  112.         allPercentiles.add(percentileP50)
  113.         allPercentiles.add(percentileP85)
  114.         allPercentiles.add(percentileP97)
  115.     }
  116.  
  117.     @RequiresApi(Build.VERSION_CODES.O)
  118.     override fun showScalesList(list: List<ScaleEntity>) {
  119.         scales = list.size
  120.         if (list.isNotEmpty()) {
  121.             list.forEach {
  122.                 var weight = it.weight.toDouble()
  123.                 if (weight < 10) {
  124.                     weight *= 1000
  125.                 }
  126.                 else if (weight >= 10 && weight < 100) {
  127.                     weight *= 10
  128.                 }
  129.                 percentileBabyScales.add(weight)
  130.                 Timber.e("showScalesList date: ${it.createdAt}")
  131.                 Timber.e("showScalesList age days: ${it.age} weeks: ${it.age!!/ DAYS_IN_WEEK}")
  132.                 percentileBabyScales2.add((it.age!! / DAYS_IN_WEEK).toDouble())
  133.             }
  134. //            percentileBabyScales.add(0.0)
  135. //            percentileBabyScales2.add(0.0)
  136.  
  137.             Collections.reverse(percentileBabyScales)
  138.             Collections.reverse(percentileBabyScales2)
  139.         }
  140.  
  141.         if (babyWeight != -1f) {
  142. //            percentileBabyScales.add(0.0)
  143. //            percentileBabyScales2.add(0.0)
  144.             percentileBabyScales2.add(/*percentileBabyScales[0]*/0.0)
  145.         }
  146.  
  147.         setupChart()
  148.         setupBabyLine()
  149.     }
  150.  
  151.  
  152.     @RequiresApi(Build.VERSION_CODES.O)
  153.     override fun onCreate(savedInstanceState: Bundle?) {
  154.         super.onCreate(savedInstanceState)
  155.         setContentView(R.layout.activity_who_graph)
  156.  
  157.         setSupportActionBar(toolbar)
  158.         supportActionBar?.setDisplayShowTitleEnabled(false)
  159.  
  160.         toolbarTitle.setText(R.string.who_graph_title)
  161.         toolbar.setNavigationOnClickListener { onBackPressed() }
  162.         toolbar.setNavigationIcon(R.drawable.ic_back)
  163.  
  164.         babyId = intent.getIntExtra(WhoGraphActivity.KEY_EXTRA_BABY_ID, 0)
  165.         babyGender = intent.getStringExtra(KEY_EXTRA_BABY_GENDER)
  166.         babyWeight = intent.getFloatExtra(KEY_EXTRA_BABY_WEIGHT, -1f)
  167.         babyName = intent.getStringExtra(KEY_EXTRA_BABY_NAME)
  168.         babyAge = intent.getIntExtra(KEY_EXTRA_BABY_AGE, 0) / DAYS_IN_WEEK
  169.         isShared = intent.getBooleanExtra(KEY_EXTRA_IS_SHARED, false)
  170.  
  171.         if (babyGender == Const.Genders.MALE) {
  172.             bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_birthday_graph_male)
  173.         }
  174.         else {
  175.             bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_birthday_graph_female)
  176.         }
  177.  
  178.         tvBabyName.text = babyName
  179.  
  180. //        birthday = this string R.string.who_graph_birthday
  181.         weeks = this string R.string.who_graph_weeks
  182. //        weeks = resources.getQuantityString(R.plurals.who_graph_weeks, i)
  183.         isDE = false
  184.         if (tvTip.text.equals("Tip")) {
  185.             birthday = " Birthday"
  186.         }
  187.         else {
  188.             isDE = true
  189.             birthday = " Geburtstag"
  190.         }
  191.         if (babyGender == Const.Genders.MALE) {
  192.             iv_baby_line.setBackgroundResource(R.drawable.bg_dotted_baby_male)
  193.             iv_baby_line2.setBackgroundResource(R.drawable.bg_dotted_baby_male)
  194.         }
  195.         else {
  196.             iv_baby_line.setBackgroundResource(R.drawable.bg_dotted_baby_female)
  197.             iv_baby_line2.setBackgroundResource(R.drawable.bg_dotted_baby_female)
  198.         }
  199.  
  200.         presentationComponent.inject(this)
  201.         presenter.attachToView(this)
  202.  
  203.         presenter.getAllPercentilesByBabyId(babyId, isShared)
  204.  
  205.  
  206.         fab?.visibility = View.INVISIBLE
  207.         fab?.setOnClickListener {
  208.             shareWhoGraphRequest()
  209.         }
  210.  
  211.         tvTip.visibility = View.INVISIBLE
  212.  
  213.         mChart.visibility = View.INVISIBLE
  214.         mChart.setNoDataText("")
  215.        
  216.         legend1.visibility = View.INVISIBLE
  217.         legend2.visibility = View.INVISIBLE
  218.         legend3.visibility = View.INVISIBLE
  219.  
  220.         setTipSpan()
  221.     }
  222.  
  223.     private fun isStoragePermissionGranted() : Boolean{
  224.         return if (Build.VERSION.SDK_INT >= 23) {
  225.             if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
  226.                     == PackageManager.PERMISSION_GRANTED) {
  227.                 true
  228.             } else {
  229.                 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
  230.                 false
  231.             }
  232.         } else { //permission is automatically granted on sdk<23 upon installation
  233.             true
  234.         }
  235. }
  236.  
  237.     private fun shareWhoGraphRequest() {
  238.         if (isStoragePermissionGranted()) {
  239.             share()
  240.         }
  241.     }
  242.  
  243.  
  244.     // Method to draw watermark
  245.     private fun mark(src:Bitmap, watermark:String, location:Point, alpha: Int, size: Int, typeface: Typeface): Bitmap {
  246.  
  247.         val w = src.width
  248.         val h = src.height
  249.         val result = Bitmap.createBitmap(w, h, src.config)
  250.  
  251.         val canvas = Canvas(result)
  252.         canvas.drawBitmap(src, 0f, 0f, null)
  253.  
  254.  
  255.         val paint = Paint()
  256.         paint.color = this color R.color.colorBlueLight
  257.         paint.alpha = alpha
  258.         paint.style = Paint.Style.FILL
  259.         paint.textSize = size.toFloat()
  260.         paint.isAntiAlias = true
  261.         paint.typeface = typeface
  262.         canvas.drawText(watermark, location.x.toFloat(), location.y.toFloat(), paint)
  263.  
  264.         var b = BitmapFactory.decodeResource(resources, R.drawable.ic_app_logo)
  265.  
  266.         val paint2 = Paint()
  267.         paint2.alpha = 200
  268.  
  269.         b = Bitmap.createScaledBitmap(b, 120, 120, false)
  270.         canvas.drawBitmap(b, 110f, 25f, paint2)
  271.  
  272.         return result;
  273.     }
  274.  
  275.     private fun share() {
  276.         val mBitmap = mChart.chartBitmap
  277.  
  278. //        Bitmap bitmap = createBitmapFromUri(uri);
  279.  
  280.         val point = Point(250, 100)
  281.  
  282.         // Creating type face
  283.         val plain = Typeface.createFromAsset(assets, "OpenSans-Regular.ttf")
  284.         val bold = Typeface.create(plain, Typeface.BOLD)
  285.  
  286.  
  287.         val newBitmap = mark(mBitmap, "www.emiltonia.de", point, 200, 50, bold)
  288. //        val bitmap = mChart.chartBitmap
  289.         val imgName = "Emiltonia_".plus(babyName).plus("_Who_Graph_".plus(getCurrentTimeStamp()))
  290.         val bitmapPath = MediaStore.Images.Media.insertImage(contentResolver, /*bitmap*/newBitmap, imgName, null)
  291.         val bitmapUri = Uri.parse(bitmapPath)
  292.         val intent = Intent()
  293.         intent.action = Intent.ACTION_SEND
  294.         intent.type = "image/*"
  295.  
  296.         intent.putExtra(Intent.EXTRA_STREAM, bitmapUri)
  297.         val shareTitle = "Share ".plus(babyName).plus(" Who Graph")
  298.         startActivity(Intent.createChooser(intent, shareTitle))
  299.     }
  300.  
  301.     override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
  302.         super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  303.  
  304.         if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  305.             share()
  306.         }
  307.     }
  308.  
  309.  
  310.     @RequiresApi(Build.VERSION_CODES.O)
  311.     private fun setupChart() {
  312.  
  313.         mChart.onChartGestureListener = this
  314.         mChart.setDrawGridBackground(false)
  315.  
  316.         mChart.description.isEnabled = false
  317.  
  318.         // enable touch gestures
  319.         mChart.setTouchEnabled(true)
  320.  
  321.         // enable scaling and dragging
  322.         mChart.isDragEnabled = true
  323.         mChart.setScaleEnabled(true)
  324.  
  325.         // if disabled, scaling can be done on x- and y-axis separately
  326.         mChart.setPinchZoom(true)
  327.  
  328.         // set an alternative background color
  329.         // mChart.setBackgroundColor(Color.GRAY);
  330.  
  331.         // create a custom MarkerView (extend MarkerView) and specify the layout
  332.         // to use for it
  333. //        val mv = MyMarkerView(this, R.layout.custom_marker_view)
  334. //        mv.setChartView(mChart) // For bounds control
  335. //        mChart.marker = mv // Set the marker to the chart
  336.  
  337. //        val xAxis = mChart.xAxis
  338. //        xAxis.enableGridDashedLine(10f, 10f, 0f)
  339.         //xAxis.setValueFormatter(new MyCustomXAxisValueFormatter());
  340.         //xAxis.addLimitLine(llXAxis); // add x-axis limit line
  341.  
  342.  
  343.         val leftAxis = mChart.axisLeft
  344.         leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
  345.         leftAxis.removeAllLimitLines() // reset all limit lines to avoid overlapping lines
  346. //        leftAxis.yOffset = 20f;
  347.         leftAxis.enableGridDashedLine(30f, 10f, 0f)
  348.         leftAxis.setDrawZeroLine(false)
  349.  
  350. //        leftAxis.
  351.  
  352.  
  353. //        mChart.setVisibleXRange(20f)
  354. //        mChart.setVisibleYRange(20f, YAxis.AxisDependency.LEFT)
  355. //        mChart.centerViewTo(20f, 50f, YAxis.AxisDependency.LEFT)
  356.  
  357. //        mChart.animateX(2500)
  358. //        mChart.invalidate();
  359.  
  360.         // get the legend (only possible after setting data)
  361.         val l = mChart.legend
  362. //        l.position = Legend.LegendPosition.LEFT_OF_CHART_INSIDE
  363.         mChart.xAxis.setDrawLabels(true)
  364.         mChart.legend.setDrawInside(false)
  365.         l.form = Legend.LegendForm.LINE
  366.         mChart.legend.isEnabled = false
  367. //        l.setDrawInside(true)
  368. //        l.addDashedLine(width: dashWidth, pattern: dashes[0], color: statisticColor)
  369.  
  370.  
  371.         // // dont forget to refresh the drawing
  372. //         mChart.invalidate();
  373.  
  374.         mChart.setBackgroundColor(Color.WHITE)
  375.  
  376.         mChart.setBorderColor(Color.TRANSPARENT)
  377.         mChart.isDragXEnabled = true
  378.         mChart.isDragYEnabled = true //false
  379.         mChart.isScaleXEnabled = true
  380.         mChart.isScaleYEnabled = true //false
  381.         mChart.viewPortHandler.setMaximumScaleX(/*5*//*8*/16f)
  382.         mChart.viewPortHandler.setMaximumScaleY(/*10*/2f)
  383.  
  384.         val xValueRenderer = XValueRenderer(
  385.                 mChart.viewPortHandler,
  386.                 mChart.xAxis,
  387.                 mChart.rendererXAxis.transformer
  388.         )
  389.         mChart.setXAxisRenderer(xValueRenderer)
  390.  
  391.         val xAxis = mChart.xAxis
  392.         xAxis.position = XAxis.XAxisPosition.BOTTOM
  393.         xAxis.gridColor = Color.LTGRAY
  394.         xAxis.setDrawGridLines(true)
  395.         xAxis.enableGridDashedLine(30f, 0f, 0f)
  396.         xAxis.textColor = Color.LTGRAY
  397.         xAxis.valueFormatter = XValueFormatter(this@WhoGraphActivity)
  398.         val light = Typeface.createFromAsset(this.assets, "OpenSans-Regular.ttf")
  399.         xAxis.typeface = light
  400. //        xAxis.labelCount = UIScreen.main.bounds.size.width > 375 ? 5 : 4
  401.         xAxis.labelCount = /*5*/4
  402.         xAxis.textColor = Color.BLACK
  403.         xAxis.yOffset = 10f
  404.         xAxis.textSize = 9f
  405.         mChart.setExtraOffsets(0f,0f,0f,10f)
  406.         //todo find out how manipulate with limits
  407. //        xAxis.axisMinimum = 0f/*self.dataProvider.leftXLimit*/
  408. //        xAxis.axisMaximum = 0f/*self.dataProvider.rightXLimit*/
  409.  
  410.         mChart.axisRight.isEnabled = false
  411.  
  412. //        mChart.setViewPortOffsets(100f,0f,-40f,0f)
  413. //        mChart.offsetLeftAndRight(100)
  414. //        mChart.setDragOffsetX(50f)
  415.  
  416.  
  417.         val yValueRenderer = YValueRenderer(
  418.                 mChart.viewPortHandler,
  419.                 mChart.getAxis(YAxis.AxisDependency.LEFT),
  420.                 mChart.rendererXAxis.transformer
  421.         )
  422.         mChart.rendererLeftYAxis = yValueRenderer
  423.  
  424.         val yAxis = mChart.getAxis(YAxis.AxisDependency.LEFT)
  425.         yAxis.setPosition(YAxis.YAxisLabelPosition./*INSIDE_CHART*/OUTSIDE_CHART)
  426.         yAxis.setDrawTopYLabelEntry(false)
  427.         yAxis.setDrawLimitLinesBehindData(false)
  428.         yAxis.axisMinimum = 0f/*self.dataProvider.lowerYLimit*/
  429.         yAxis.axisMaximum = 10000f/*self.dataProvider.upperYLimit*/
  430.         yAxis.labelCount = ((yAxis.axisMaximum - yAxis.axisMinimum).toInt()) / 1000
  431.         yAxis.gridColor = Color.LTGRAY
  432.         yAxis.setDrawGridLines(true)
  433.         yAxis.enableGridDashedLine(30f, 0f, 0f)
  434.         yAxis.textColor = Color.BLACK
  435.         yAxis.valueFormatter = YValueFormatter()
  436. //        yAxis.xOffset = yAxis.xOffset - 4f/*yLabelRectInset*/
  437. //        yAxis.xOffset -= 40f
  438.  
  439. //        mChart.setVisibleXRange(1f, 10f)
  440.         mChart.zoom(3.692f, 1f, 1f, 1f, yAxis.axisDependency)
  441. //        mChart.centerViewTo(10f, 10f, yAxis.axisDependency)
  442.     }
  443.  
  444.     private fun setTipSpan() {
  445.         val spannableText = SpannableStringBuilder()
  446.         spannableText.append(this string R.string.who_graph_tip_text)
  447.         val registration = this string R.string.who_graph_tip
  448.         spannableText.addClickableSpannable(registration,
  449.                 this color R.color.colorAccent
  450.         ) {
  451. //            RegistrationActivity.startActivity(this)
  452.         }
  453.         tvTip.text = spannableText
  454.         tvTip.movementMethod = LinkMovementMethod.getInstance()
  455.     }
  456.  
  457.     private fun setupBabyLine() {
  458.  
  459.         if (scales > 0 || babyWeight != -1f) {
  460.  
  461.             val values2 = ArrayList<Entry>()
  462.  
  463. //            Timber.e("setupBabyLine scales = $scales")
  464.  
  465.             var icon: Drawable? = null
  466.             if (babyGender == Const.Genders.MALE) {
  467.                 icon = resources.getDrawable(R.drawable.ic_birthday_graph_male)
  468.             }
  469.             else {
  470.                 icon = resources.getDrawable(R.drawable.ic_birthday_graph_female)
  471.             }
  472.             if (babyWeight != -1f) {
  473. //                values2.add(Entry(0f, 0f))
  474.                 values2.add(Entry(percentileBabyScales2[0].toFloat() ,babyWeight, icon))
  475.             }
  476.             else {
  477. //                values2.add(Entry(percentileBabyScales2[0].toFloat(), percentileBabyScales[0].toFloat(), icon))
  478.  
  479.                 for (i in 0 until scales) {
  480. //                    Timber.e("baby value = X: ${percentileBabyScales2[i].toFloat()} Y: ${percentileBabyScales[i].toFloat()}")
  481.                     values2.add(Entry(percentileBabyScales2[i].toFloat(), percentileBabyScales[i].toFloat()))
  482. //                values2.add(Entry(i.toFloat(), percentileBabyScales[i].toFloat()))
  483.                 }
  484.                 values2[0] = Entry(percentileBabyScales2[0].toFloat(), percentileBabyScales[0].toFloat(), icon)
  485.             }
  486.  
  487. //            Timber.e("BBBB: ${percentileBabyScales2[0].toFloat()} : $babyWeight")
  488.             val line = LineDataSet(values2, babyName)
  489.  
  490.             // set the line to be drawn like this "- - - - - -"
  491.             line.enableDashedLine(10f, 0f, 0f)
  492.             line.enableDashedHighlightLine(10f, 0f, 0f)
  493.  
  494.  
  495.             if (babyGender == Const.Genders.MALE) {
  496.                 line.color = Color.rgb(152, 210, 212)
  497.                 line.setCircleColor(Color.rgb(152, 210, 212))
  498.             } else {
  499.                 line.color = Color.rgb(221, 160, 199)
  500.                 line.setCircleColor(Color.rgb(221, 160, 199))
  501.             }
  502. //        line.setCircleColorHole(line.colors[0])
  503.             line.lineWidth = 3f
  504.             line.circleRadius = 5f
  505.             line.circleHoleRadius = line.circleRadius * 0.8f
  506.             line.axisDependency = YAxis.AxisDependency.LEFT
  507.             line.setDrawValues(false)
  508.             line.setDrawIcons(true)
  509. //        line.valueTextSize = 10f
  510.             line.setDrawVerticalHighlightIndicator(false)
  511.             line.setDrawHorizontalHighlightIndicator(false)
  512.  
  513. //            line.formLineWidth = 1f
  514. //            line.formSize = 15f
  515.  
  516. //            line.getEntryForIndex(0).icon = drawable(R.drawable.ic_access)
  517.  
  518. //            line.mode = LineDataSet.Mode.CUBIC_BEZIER
  519.  
  520.  
  521.             data.addDataSet(line)
  522.             setPercentilesData()
  523.  
  524. //            mChart.moveViewToX(scales.toFloat())
  525. //            mChart.setScaleMinima(10f,1f)
  526.  
  527.             mChart.data = data
  528.             mChart.data.isHighlightEnabled = false
  529.             mChart.description = null
  530.  
  531. //            mChart.renderer = MyLineChartRender(mChart, mChart.animator, mChart.viewPortHandler, this@WhoGraphActivity)
  532.  
  533.             mChart.invalidate()
  534.  
  535.             fab?.visibility = View.VISIBLE
  536.             tvTip.visibility = View.VISIBLE
  537.             mChart.visibility = View.VISIBLE
  538.             legend1.visibility = View.VISIBLE
  539.             legend2.visibility = View.VISIBLE
  540.             legend3.visibility = View.VISIBLE
  541.         }
  542.         else {
  543.             Toast.makeText(this@WhoGraphActivity, babyName.plus(" have no scales."), Toast.LENGTH_LONG).show()
  544.         }
  545.     }
  546.  
  547.  
  548.     class YValueRenderer(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, trans: Transformer?) : YAxisRenderer(viewPortHandler, yAxis, trans) {
  549.  
  550.         override fun drawYLabels(c: Canvas?, fixedPosition: Float, positions: FloatArray?, offset: Float) {
  551.             super.drawYLabels(c, fixedPosition, positions, offset)
  552.  
  553. //            c!!.drawText("MY_TEXT_111", fixedPosition, fixedPosition, mAxisLabelPaint)
  554.  
  555. //            Timber.e("YValueRenderer: Y: ${positions!![0]} : ${positions!![1]} : ${positions!![2]} : ${positions!![3]}")
  556.             for ((key, v) in positions!!.withIndex()) {
  557. //                Timber.e("POS: $v")
  558.             }
  559.         }
  560.  
  561.         override fun renderAxisLabels(context: Canvas) {
  562.  
  563. //            Timber.e("renderAxisLabels go 1")
  564.  
  565.             if (mYAxis == null) return
  566.  
  567.             if (!mYAxis.isEnabled || !mYAxis.isDrawLabelsEnabled) return
  568.  
  569. //            Timber.e("renderAxisLabels go 2")
  570.  
  571.             val xoffset = mYAxis.xOffset
  572.             val yoffset = Utils.calcTextHeight(mAxisLabelPaint, "A") / 2.5 + mYAxis.yOffset
  573.             val dependency = mYAxis.axisDependency
  574.             val labelPosition = mYAxis.labelPosition
  575.             var xPos = 0f
  576.             val textAlign = mAxisLabelPaint
  577.  
  578.  
  579.             if (dependency == YAxis.AxisDependency.LEFT) {
  580.                 if (labelPosition == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
  581.                     textAlign.textAlign = Paint.Align.RIGHT
  582.                     xPos = mViewPortHandler.offsetLeft() - xoffset
  583.                 } else {
  584.                     textAlign.textAlign = Paint.Align.LEFT
  585.                     xPos = mViewPortHandler.offsetLeft() + xoffset
  586.                 }
  587.             } else {
  588.                 if (labelPosition == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
  589.                     textAlign.textAlign = Paint.Align.LEFT
  590.                     xPos = mViewPortHandler.contentRight() + xoffset
  591.                 } else {
  592.                     textAlign.textAlign = Paint.Align.RIGHT
  593.                     xPos = mViewPortHandler.contentRight() - xoffset
  594.                 }
  595.             }
  596.  
  597.             val fixedPosition = xPos
  598.             val positions = transformedPositions
  599. //            val offset = yoffset - yAxis.labelFont.lineHeight
  600.             val offset = yoffset - Utils.calcTextHeight(mAxisLabelPaint, "B")
  601. //            val offset = 0f
  602.  
  603.             var from = -1
  604.             if (mYAxis.isDrawBottomYLabelEntryEnabled) from = 0
  605.             else from = 1
  606.             var to = -1
  607.             if (mYAxis.isDrawTopYLabelEntryEnabled) to = mYAxis.mEntryCount
  608.             else to = mYAxis.mEntryCount - 1
  609. //            val attributes = [NSAttributedStringKey.font: labelFont]
  610.             val col = Color.LTGRAY
  611.  
  612.             for (i in from..to step 1) {
  613.  
  614.                 val text = mYAxis.getFormattedLabel(i)
  615.                 val point = /*CGPoint*/MPPointF(fixedPosition, ((positions[i] + offset).toFloat()))
  616. //                val textSize = text.size(withAttributes: attributes)
  617. //                val textSize = textAlign.textSize
  618.                 val textSize = textAlign.textSize
  619.  
  620.                 if (textAlign == Paint.Align.CENTER) {
  621. //                    Timber.e("textAlign == Paint.Align.CENTER")
  622.                     point.x -= textSize/*.width*/ / 2.0f
  623.                 } else if (textAlign == YAxis.AxisDependency.RIGHT) {
  624.                     point.x -= textSize/*.width*/
  625.                 }
  626.                 else if (textAlign == YAxis.AxisDependency.LEFT) {
  627.                     point.x += textSize
  628.                 }
  629.  
  630.                 val rect = RectF(point.x, point.y, 4f, 10f)
  631.                 val path = Path()
  632.                 path.addRect(rect, Path.Direction.CW)
  633.  
  634. //                context.clipOutPath(path)
  635. //                var paint = Paint()
  636. //                paint.color = Color.RED
  637. //                paint.style = Paint.Style.FILL
  638. //                context.drawPaint(paint)
  639.  
  640. //                paint.color = Color.GREEN
  641. //                paint.textSize = 20f
  642.  
  643. //                val paint2 = Paint()
  644. //                paint2.color = Color.GRAY
  645.  
  646. //                paint2.strokeWidth = 40f
  647. //                paint2.color = Color.argb(0.75f, 0.8f, 0.8f, 0.8f)
  648. //                context.drawLine(point.x-5, point.y+5, point.x+95, point.y+5, paint2)
  649.  
  650. //                context.drawCircle(point.x+50, point.y, 50f, paint2)
  651. //                context.drawText("Some Text", point.x, point.y, paint)
  652.  
  653. //                context.drawColor(Color.RED)
  654. //                context.drawCircle(100f,100f,30f, paint)
  655. //                path.rewind()
  656. //                context.drawPath(path, paint)
  657.  
  658.  
  659. //                UIGraphicsPushContext(context)
  660. //                col.set()
  661. //                path.fill()
  662. //                UIGraphicsPopContext()
  663.  
  664. //                mAxisLabelPaint.
  665.  
  666.                 /*val rect = CGRect(point, textSize).insetBy(-yLabelRectInset, 0)
  667.                 val path = UIBezierPath.init(rect, yLabelRectInset)
  668.  
  669.                 UIGraphicsPushContext(context)
  670.                 col.set()
  671.                 path.fill()
  672.                 UIGraphicsPopContext()*/
  673.             }
  674.  
  675.             super.renderAxisLabels(context)
  676.         }
  677.     }
  678.  
  679.     class XValueRenderer(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, trans: Transformer?) : XAxisRenderer(viewPortHandler, xAxis, trans) {
  680.  
  681.         override fun drawLabel(context: Canvas, formattedLabel: String, x: Float, y: Float, anchor: MPPointF, angleRadians: Float) {
  682.  
  683.             var bday = ""
  684.             if (!isDE) {
  685.                 bday = " Birthday"
  686.             } else bday = " Geburtstag"
  687. //            if (formattedLabel == /*" Birthday"*/bday) {
  688. //            Timber.e("DDD: $bday : $formattedLabel")
  689.             if (formattedLabel == bday) {
  690.  
  691. //                context.drawBitmap(bitmap, x-20, y-50, null)
  692.  
  693.                 setBirthdayColor()
  694.  
  695. //                val paint = Paint()
  696. //                paint.color = Color.RED
  697. //                paint.color = Color.argb(0.75f, 0.8f, 0.8f, 0.8f)
  698. //                paint.strokeWidth = 4f
  699. //                context.drawLine(x-5, y+5, x+95, y+5, paint)
  700. //                context.drawLine(x-5, y+5, X1.toFloat(), Y1.toFloat(), paint)
  701. //                Timber.e("POSSS: $X1 : $Y1")
  702. //                context.drawLine(x-5, y+5, X1.toFloat(), Y1.toFloat()*10, paint)
  703.  
  704.  
  705.                 super.drawLabel(context, formattedLabel, x, y, anchor, angleRadians)
  706.                 return
  707.             }
  708.             else {
  709.                 mAxisLabelPaint.color = Color.BLACK
  710.             }
  711. //            Timber.e("XValueRenderer: X: $x : Y: $y")
  712.             super.drawLabel(context, formattedLabel, x, y, anchor, angleRadians)
  713.         }
  714.  
  715.         private fun setBirthdayColor() {
  716.             if (babyGender == Const.Genders.MALE) {
  717.                 mAxisLabelPaint.color = Color.rgb(152, 210, 212)
  718.             }
  719.             else {
  720.                 mAxisLabelPaint.color = Color.rgb(221, 160, 199)
  721.             }
  722.         }
  723.     }
  724.  
  725.  
  726.     class XValueFormatter(val context: Context): IndexAxisValueFormatter() {
  727.  
  728.         override fun getFormattedValue(value: Float, axis: AxisBase?): String {
  729.             if (value == 0f)
  730. //                return R.string.who_graph_birthday
  731. //                return " Birthday"dd
  732.                 return birthday
  733.             if (value < 1)
  734.                 return ""
  735.             val i = value.toInt()
  736. //            return i.toString().plus(" weeks")
  737. //            var weeks = ""
  738. //            if (birthday.equals(" Birthday")) {
  739. //                weeks =
  740. //            }
  741.             return context.resources.getQuantityString(R.plurals.who_graph_weeks, i, i)
  742. //            return i.toString().plus(" ").plus(weeks)
  743.         }
  744.     }
  745.  
  746.     class YValueFormatter: IndexAxisValueFormatter() {
  747.  
  748.         override fun getFormattedValue(value: Float, axis: AxisBase?): String {
  749.             var stroke = value.toInt().toString()
  750.             if (value == 0f) return ""
  751.             else {
  752.                 if (value > 1000f)
  753.                     stroke = stroke.substring(0, 1).plus(" ").plus(stroke.substring(1, stroke.length))
  754.             }
  755.             return stroke.plus(" g")
  756.         }
  757.     }
  758.  
  759.     private fun getCurrentTimeStamp(): String? {
  760.         return try {
  761.             val dateFormat = SimpleDateFormat("yyyy-MM-dd_HH:mm:ss")
  762.             dateFormat.format(Date())
  763.         } catch (e: Exception) {
  764.             e.printStackTrace()
  765.             null
  766.         }
  767.     }
  768.  
  769.     private fun setPercentilesData() {
  770.  
  771.         for ((pos, value) in allPercentiles.withIndex()) {
  772.             val values = ArrayList<Entry>()
  773.  
  774. //            Timber.e("SetAllData until scales = $scales")
  775.             for (i in 0 until /*scales*/96) {
  776.                 values.add(Entry(i.toFloat(), value[i].toFloat()))
  777.             }
  778.  
  779.             val set = LineDataSet(values,"")
  780.             set.setDrawIcons(false)
  781.  
  782.             set.enableDashedLine(allDashedLinesLength[pos], allDashedLinesSpaceLength[pos], 0f)
  783.             set.color = Color.GRAY
  784.             set.setCircleColor(Color.GRAY)
  785.             set.lineWidth = 1.5f
  786.             set.circleRadius = 2f
  787.             set.setDrawCircles(false)
  788.             set.setDrawCircleHole(false)
  789.             set.setDrawValues(false)
  790.             set.setDrawFilled(false)
  791.             set.formLineWidth = 1f
  792.             set.formSize = 15f
  793.  
  794. //            set.fillColor = Color.RED
  795. //            set.fillDrawable = this drawable R.drawable.ic_access
  796. //            data.setValueTextColor(Color.RED)
  797.             data.addDataSet(set)
  798.         }
  799.     }
  800.  
  801.     override  fun onChartFling(me1: MotionEvent, me2: MotionEvent, velocityX: Float, velocityY: Float) {
  802.     }
  803.  
  804.     override   fun onChartScale(me: MotionEvent, scaleX: Float, scaleY: Float) {
  805.         recalculateXLimits()
  806.     }
  807.  
  808.     override  fun onChartTranslate(me: MotionEvent, dX: Float, dY: Float) {
  809.         recalculateXLimits()
  810.     }
  811.  
  812.     private fun recalculateXLimits() {
  813.  
  814.         val lineChartView = mChart
  815.         val minX = -4.0 / mChart.scaleX
  816.  
  817.         if (lineChartView.lowestVisibleX < minX) {
  818.             lineChartView.moveViewToX(minX.toFloat())
  819.             lineChartView.invalidate()
  820.         }
  821.     }
  822.  
  823.     override fun onChartGestureEnd(me: MotionEvent?, lastPerformedGesture: ChartTouchListener.ChartGesture?) {
  824.         // no-opt
  825.     }
  826.  
  827.     override fun onChartSingleTapped(me: MotionEvent?) {
  828.         // no-opt
  829.     }
  830.  
  831.     override fun onChartGestureStart(me: MotionEvent?, lastPerformedGesture: ChartTouchListener.ChartGesture?) {
  832.         // no-opt
  833.     }
  834.  
  835.     override fun onChartLongPressed(me: MotionEvent?) {
  836.         // no-opt
  837.     }
  838.  
  839.     override fun onChartDoubleTapped(me: MotionEvent?) {
  840.         // no-opt
  841.     }
  842. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement