热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android运动健康睡眠自定义控件的实现

这篇文章主要介绍了Android实现运动健康睡眠自定义控件的方法,帮助大家更好的理解和学习使用Android开发,感兴趣的朋友可以了解下

效果图

代码

/**
 *
 * 日图表
 * zrj 2020/8/25
 */
class SleepDayChart(context: Context, attrs: AttributeSet?) : View(context, attrs) {
  //屏幕宽高
  private var scrWidth = 0f
  private var scrHeight = 0f
  private var xData: Array = arrayOf("20:00", "02:00", "08:00", "14:00", "20:00")
  private var sleepsData: Sleep? = null
  private lateinit var paintLine: Paint
  private lateinit var paintGradientLine: Paint
  private lateinit var paintXText: Paint
  private lateinit var paintSleep: Paint
  private lateinit var paintPillar: Paint
  private lateinit var paintRound: Paint
  private lateinit var paintBessel: Paint

  private var xSlider = 0f //滑块的x轴位置

  private var mPath: Path
  private val curveCircleRadius = 12f.dp

  // the coordinates of the first curve
  private val mFirstCurveStartPoint = Point()
  private val mFirstCurveEndPoint = Point()
  private val mFirstCurveControlPoint1 = Point()
  private val mFirstCurveControlPoint2 = Point()

  //the coordinates of the second curve
  private var mSecOndCurveStartPoint= Point()
  private val mSecOndCurveEndPoint= Point()
  private val mSecondCurveControlPoint1 = Point()
  private val mSecondCurveControlPoint2 = Point()


  init {
    setLayerType(LAYER_TYPE_SOFTWARE, null)
    mPath = Path()
    initPaint()
  }

  /**
   * 初始化画笔
   */
  private fun initPaint() {

    paintLine = Paint()
    paintLine.style = Paint.Style.STROKE
    paintLine.strokeWidth = 1f
    paintLine.color = context.colorCompat(R.color.e6e6e6_2e2e2e)

    paintGradientLine = Paint()
    paintGradientLine.style = Paint.Style.STROKE
    paintGradientLine.strokeWidth = 1f

    paintXText = Paint()
    paintXText.isAntiAlias = true
    paintXText.strokeWidth = 1f
    paintXText.textSize = 12f.sp
    paintXText.textAlign = Paint.Align.CENTER
    paintXText.color = context.colorCompat(R.color.color_on_surface)


    paintSleep = Paint()
    paintSleep.style = Paint.Style.FILL
    paintSleep.isAntiAlias = true
    paintSleep.color = context.colorCompat(R.color.blue_7fbeff)

    paintPillar = Paint()
    paintPillar.style = Paint.Style.FILL
    paintPillar.isAntiAlias = true
    paintPillar.color = context.colorCompat(R.color.blue_7fbeff)

    paintRound = Paint()
    paintRound.style = Paint.Style.FILL
    paintRound.isAntiAlias = true
    paintRound.color = context.colorCompat(R.color.ffffff_6e6e6e)

    paintBessel = Paint()
    paintBessel.style = Paint.Style.FILL
    paintBessel.isAntiAlias = true
    paintBessel.color = context.colorCompat(R.color.f2f2f2_1d1d1d)
  }

  override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
    super.onSizeChanged(w, h, oldw, oldh)
    scrWidth = width.toFloat()
    scrHeight = height.toFloat()
    ySpacing = scrHeight / 8f //y轴分8份

    //底部圆滑块可以滑动的范围
    xWithStart = margin * 3
    xWithEnd = scrWidth - margin * 3
    xSlider = scrWidth / 2
    xSpacing = (xWithEnd - xWithStart) / (xData.size - 1)

  }

  override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    parent.requestDisallowInterceptTouchEvent(true)
    return super.dispatchTouchEvent(ev)
  }

  private var mDownX = 0f
  private var mDownY = 0f
  private var isSlider = false

  @SuppressLint("ClickableViewAccessibility")
  override fun onTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
      MotionEvent.ACTION_DOWN -> {
        mDownX = event.x
        mDownY = event.y
        isSlider = abs(event.x - xSlider) <60f && abs(event.y - ySpacing * 7) <60f
        return isSlider
      }
      MotionEvent.ACTION_MOVE ->
        if (abs(event.y - mDownY)  xWithEnd) {
              xSlider = xWithEnd
            }
            invalidate()
          }
        }


      MotionEvent.ACTION_UP -> {
        if (!isSlider) {
          if (abs(event.x - mDownX) 
        val x = xWithStart + xSpacing * index
        val dis = abs(x - xSlider)
        var y = ySpacing * 7 - 10f.dp
        if (dis  1f) {
            temp = 1f
          }
          y1 -= 60f * temp
        } else {
          paintXText.typeface = Typeface.DEFAULT
        }

        canvas.drawText(s1, xWithStart, y1, paintXText)
        canvas.drawText(startDay, xWithStart, y1 - 40f, paintXText)
        val hour = "${if (wakeUp / 60 <10) "0" else ""}${wakeUp / 60}"
        val minute = "${if (wakeUp % 60 <10) "0" else ""}${wakeUp % 60}"
        val s2 =
          "${context.getString(R.string.rise_time)} $hour:$minute"
        val dis2 = abs(xWithEnd - paintXText.measureText(s2) / 2 - xSlider)
        var y2 = ySpacing * 7 - 10f
        if (dis2 
        when (item.status) {
          3, 4 -> { //清醒
            endColor = Color.parseColor("#fdc221")
            paintSleep.color = Color.parseColor("#fdc221")
            paintPillar.color = Color.parseColor("#f9eec1")
            top = 1f
            bottom = 2f
          }
          12 -> { //快速眼动
            endColor = Color.parseColor("#fd817c")
            paintSleep.color = Color.parseColor("#fd817c")
            paintPillar.color = Color.parseColor("#4dfd817c")
            top = 2f
            bottom = 3f
          }
          0, 1 -> { //浅
            endColor = Color.parseColor("#c64be4")
            paintSleep.color = Color.parseColor("#c64be4")
            paintPillar.color = Color.parseColor("#e8c3f1")
            top = 3f
            bottom = 4f
          }
          2 -> { //深
            endColor = Color.parseColor("#8a2be2")
            paintSleep.color = Color.parseColor("#8a2be2")
            paintPillar.color = Color.parseColor("#d6b9f1")
            top = 4f
            bottom = 5f
          }
        }

        if (xSlider  xWithStart + xSpacing * duration) {
          onDaySelectListener&#63;.invoke(index, item)

          canvas.drawRect(
            RectF(
              xWithStart + xSpacing * duration,
              ySpacing * top + 10f,
              xWithStart + xSpacing * (duration + item.duration),
              ySpacing * 7
            ), paintPillar
          )
        }

        canvas.drawRoundRect(
          RectF(
            xWithStart + xSpacing * duration - 1f,
            ySpacing * top,
            xWithStart + xSpacing * (duration + item.duration) + 1f,
            ySpacing * bottom
          ), 10f, 10f, paintSleep
        )

        if (index > 0 && index  10f) {

              val path1 = Path()
              path1.moveTo(xWithStart + xSpacing * duration, ySpacing * tempTop)
              path1.lineTo(
                xWithStart + xSpacing * duration - 8f,
                ySpacing * tempTop + 6f
              )
              path1.lineTo(xWithStart + xSpacing * duration, ySpacing * tempTop + 12f)
              path1.close()
              paintSleep.color = startColor
              canvas.drawPath(path1, paintSleep)
            }


            if (xSpacing * item.duration > 10f) {

              val path2 = Path()
              path2.moveTo(xWithStart + xSpacing * duration, ySpacing * tempBottom)
              path2.lineTo(
                xWithStart + xSpacing * duration + 8f,
                ySpacing * tempBottom - 6f
              )
              path2.lineTo(
                xWithStart + xSpacing * duration,
                ySpacing * tempBottom - 12f
              )
              path2.close()
              paintSleep.color = endColor
              canvas.drawPath(path2, paintSleep)
            }

          } else {
            tempBottom = tempTop + 0.1f
            tempTop = bottom - 0.1f
            colors[0] = endColor
            colors[1] = startColor

            if (xSpacing * preDuration > 10f) {

              val path1 = Path()
              path1.moveTo(xWithStart + xSpacing * duration, ySpacing * tempBottom)
              path1.lineTo(
                xWithStart + xSpacing * duration - 8f,
                ySpacing * tempBottom - 6f
              )
              path1.lineTo(
                xWithStart + xSpacing * duration,
                ySpacing * tempBottom - 12f
              )
              path1.close()
              paintSleep.color = startColor
              canvas.drawPath(path1, paintSleep)
            }


            if (xSpacing * item.duration > 10f) {

              val path2 = Path()
              path2.moveTo(xWithStart + xSpacing * duration, ySpacing * tempTop)
              path2.lineTo(
                xWithStart + xSpacing * duration + 8f,
                ySpacing * tempTop + 6f
              )
              path2.lineTo(xWithStart + xSpacing * duration, ySpacing * tempTop + 12f)
              path2.close()
              paintSleep.color = endColor
              canvas.drawPath(path2, paintSleep)
            }
          }

          val mLinearGradient = LinearGradient(
            xWithStart + xSpacing * duration,
            ySpacing * tempTop,
            xWithStart + xSpacing * duration,
            ySpacing * tempBottom, colors, null, Shader.TileMode.MIRROR
          )
          paintGradientLine.shader = mLinearGradient

          canvas.drawLine(
            xWithStart + xSpacing * duration,
            ySpacing * tempTop,
            xWithStart + xSpacing * duration,
            ySpacing * tempBottom,
            paintGradientLine
          )
        }
        tempTop = top
        tempBottom = bottom
        preDuration = item.duration
        duration += item.duration
        startColor = endColor
      }
    }
  }

  private fun drawBessel(canvas: Canvas) {
    // 第一条曲线开始点
    mFirstCurveStartPoint[(xSlider - curveCircleRadius * 3).toInt()] = (ySpacing * 7).toInt()
    // 第一条曲线结束点
    mFirstCurveEndPoint[xSlider.toInt()] =
      (ySpacing * 7 - curveCircleRadius - curveCircleRadius / 4).toInt()
    // 第二条开始点
    mSecOndCurveStartPoint= mFirstCurveEndPoint
    mSecondCurveEndPoint[(xSlider + curveCircleRadius * 3).toInt()] = (ySpacing * 7).toInt()

    // 第一条控制点
    mFirstCurveControlPoint1[(mFirstCurveStartPoint.x + curveCircleRadius + curveCircleRadius / 4).toInt()] =
      mFirstCurveStartPoint.y
    mFirstCurveControlPoint2[(mFirstCurveEndPoint.x - curveCircleRadius * 2 + curveCircleRadius).toInt()] =
      mFirstCurveEndPoint.y
    // 第二条控制点
    mSecondCurveControlPoint1[(mSecondCurveStartPoint.x + curveCircleRadius * 2 - curveCircleRadius).toInt()] =
      mSecondCurveStartPoint.y
    mSecondCurveControlPoint2[(mSecondCurveEndPoint.x - curveCircleRadius - curveCircleRadius / 4).toInt()] =
      mSecondCurveEndPoint.y
    mPath.reset()
    mPath.moveTo(0f, ySpacing * 7)
    mPath.lineTo(mFirstCurveStartPoint.x.toFloat(), mFirstCurveStartPoint.y.toFloat())
    mPath.cubicTo(
      mFirstCurveControlPoint1.x.toFloat(), mFirstCurveControlPoint1.y.toFloat(),
      mFirstCurveControlPoint2.x.toFloat(), mFirstCurveControlPoint2.y.toFloat(),
      mFirstCurveEndPoint.x.toFloat(), mFirstCurveEndPoint.y.toFloat()
    )
    mPath.cubicTo(
      mSecondCurveControlPoint1.x.toFloat(), mSecondCurveControlPoint1.y.toFloat(),
      mSecondCurveControlPoint2.x.toFloat(), mSecondCurveControlPoint2.y.toFloat(),
      mSecondCurveEndPoint.x.toFloat(), mSecondCurveEndPoint.y.toFloat()
    )
    mPath.lineTo(scrWidth, ySpacing * 7)
    mPath.lineTo(scrWidth, scrHeight)
    mPath.lineTo(0f, scrHeight)
    mPath.close()

    //底部灰色
    canvas.drawPath(mPath, paintBessel)
    //底部滑块
    canvas.drawCircle(xSlider, ySpacing * 7 + 5f, curveCircleRadius, paintRound)
  }

  private var startDay = ""
  private var endDay = ""

  fun setValue(value: Sleep&#63;, startDay: String, endDay: String): SleepDayChart {
    this.startDay = startDay
    this.endDay = endDay
    this.sleepsData = value
    if (sleepsData == null) {
      xSpacing = (xWithEnd - xWithStart) / (xData.size - 1)
    } else {
      sleepsData&#63;.let {
        xSpacing = (xWithEnd - xWithStart) / it.total //时间段分割成分钟
      }
    }
    postInvalidate()
    return this
  }

  private fun drawGradientLine(canvas: Canvas) {
    if (sleepsData == null) {
      canvas.drawText(
        context.getString(R.string.no_sleep_data),
        scrWidth / 2f,
        scrHeight / 2f,
        paintXText
      )
    } else {
      val mLinearGradient = LinearGradient(
        xSlider, ySpacing, xSlider, ySpacing * 6,
        intArrayOf(
          context.colorCompat(R.color.ffffff_262626), Color.parseColor("#0e83ff"),
          context.colorCompat(R.color.ffffff_262626)
        ), null, Shader.TileMode.MIRROR
      )
      paintGradientLine.shader = mLinearGradient

      if (ySpacing > 0) {
        canvas.drawLine(xSlider, ySpacing, xSlider, ySpacing * 6, paintGradientLine)
      }
    }
  }

  private var onDaySelectListener: ((index: Int, item: SleepItem) -> Unit)&#63; = null

  fun setOnDaySelectListener(l: ((index: Int, item: SleepItem) -> Unit)): SleepDayChart {
    this.OnDaySelectListener= l
    return this
  }
}


以上就是Android实现运动健康睡眠自定义控件的详细内容,更多关于Android 实现自定义控件的资料请关注其它相关文章!


推荐阅读
  • Python多线程详解与示例
    本文介绍了Python中的多线程编程,包括僵尸进程和孤儿进程的概念,并提供了具体的代码示例。同时,详细解释了0号进程和1号进程在系统中的作用。 ... [详细]
  • 本文将介绍如何在混合开发(Hybrid)应用中实现Native与HTML5的交互,包括基本概念、学习目标以及具体的实现步骤。 ... [详细]
  • 如何解决8080端口被占用问题
    本文介绍了如何通过命令行和任务管理器查找并终止占用8080端口的进程,以确保该端口能够正常使用。 ... [详细]
  • Excel 数据分析基础
    Excel 是数据分析中最基本且强大的工具之一,具备多种实用功能和操作方法。本文将简要介绍 Excel 的不同版本及其兼容性问题,并探讨在处理大数据时的替代方案。 ... [详细]
  • 本文介绍了如何在 ASP.NET 中设置 Excel 单元格格式为文本,获取多个单元格区域并作为表头,以及进行单元格合并、赋值、格式设置等操作。 ... [详细]
  • LDAP服务器配置与管理
    本文介绍如何通过安装和配置SSSD服务来统一管理用户账户信息,并实现其他系统的登录调用。通过图形化交互界面配置LDAP服务器,确保用户账户信息的集中管理和安全访问。 ... [详细]
  • Android 自定义 RecycleView 左滑上下分层示例代码
    为了满足项目需求,需要在多个场景中实现左滑删除功能,并且后续可能在列表项中增加其他功能。虽然网络上有很多左滑删除的示例,但大多数封装不够完善。因此,我们尝试自己封装一个更加灵活和通用的解决方案。 ... [详细]
  • 如果应用程序经常播放密集、急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了。因为MediaPlayer存在如下缺点:1)延时时间较长,且资源占用率高 ... [详细]
  • 本文详细介绍了 Charles 工具的下载、安装、配置及使用方法,特别针对 HTTP 和 HTTPS 协议的数据抓取进行了说明。 ... [详细]
  • 网络爬虫的规范与限制
    本文探讨了网络爬虫引发的问题及其解决方案,重点介绍了Robots协议的作用和使用方法,旨在为网络爬虫的合理使用提供指导。 ... [详细]
  • 本文介绍了 AngularJS 中的 $compile 服务及其用法,通过示例代码展示了如何使用 $compile 动态编译和链接 HTML 元素。 ... [详细]
  • javax.mail.search.BodyTerm.matchPart()方法的使用及代码示例 ... [详细]
  • 本文详细介绍了 Python 中 thread 和 threading 模块的使用方法,并提供了丰富的示例和解释。文章首发于 HURUWO 的博客小站,本平台进行同步备份发布。如遇图片加载失败或有任何疑问,欢迎前往原博客留言。 ... [详细]
  • Flutter 2.* 路由管理详解
    本文详细介绍了 Flutter 2.* 中的路由管理机制,包括路由的基本概念、MaterialPageRoute 的使用、Navigator 的操作方法、路由传值、命名路由及其注册、路由钩子等。 ... [详细]
  • [c++基础]STL
    cppfig15_10.cppincludeincludeusingnamespacestd;templatevoidprintVector(constvector&integer ... [详细]
author-avatar
guan
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有