欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android自定义view实现钟表效果

程序员文章站 2022-07-05 19:34:43
本文实例为大家分享了android view实现钟表的具体代码,供大家参考,具体内容如下 先看效果图: 自定义view大家肯定已经不陌生了,所以直接今天直接步入正题:如何利用c...

本文实例为大家分享了android view实现钟表的具体代码,供大家参考,具体内容如下

先看效果图:

android自定义view实现钟表效果

自定义view大家肯定已经不陌生了,所以直接今天直接步入正题:如何利用canvas去绘制出一个钟表

当然绘制之前我们必须进行测量(重写onmeasure),根据自己的规则去测量,这暂时是将控件限制为一个正方形。

首先我们先把钟表分解,看它由哪几部分组成。如上图:钟表包括表盘(刻度)和表针还有文字构成。

分清结构之后我们再明确canvas需要画什么,表盘的构成其实就是外层一个圆,然后上面是有规律的线段,表针就是三个长短不一的线段,再加上12个钟点文字。这样一分析是不是发现调用canvas的drawcircle、drawline和drawtext就可以完成钟表的绘制了。

既然明确了我们绘制所需要的方法,那么就开始重头戏了,告诉canvas在哪绘制这些零件。

最外层的圆是最简单的,我们只需要以控件的中心为圆心,控件的宽度一半为半径画一个圆就可以了。

接下来就是难点一了,这些刻度怎么办呢,其实我们不难发现其中的规律,每个刻度之间的弧度是一样的,那这样我们是不是可以通过旋转画布就可以实现这些刻度的绘制呢,答案是肯定的。

难点二,文字又该如何绘制,难道也通过旋转画布吗,但是你想一下,假如通过旋转画布去绘制文字,那有些文字可是会颠倒的,这并不是我们想要的结果,那该怎么办,这时候我们只能通过数学计算老老实实的计算每个文字的起始坐标,这些坐标并没有想象中的复杂,我们可以根据中心点的位置和偏移角度(当然还需要考虑文字的宽度)算出。

难点三,绘制表针,其实文字绘制出来,那么同样可以根据中心点和偏移角度算出表针的起始坐标和结束坐标
表心就是一个实体的圆,这个就简单了。

好像还没说时分秒是怎么确定的,这当然是通过系统时间获取的了。说到这里似乎一个静态钟表已经绘制出来了,接下来让它动起来就可以了。在这我们启动一个线程,让它隔一秒钟进行一次重绘即可。

下面我直接贴一下代码把,代码是用kotlin实现(这不是重点)的

package com.example.commonui.widget
 
import android.annotation.suppresslint
import android.content.context
import android.graphics.canvas
import android.graphics.color
import android.graphics.paint
import android.os.handler
import android.os.message
import android.util.attributeset
import android.view.view
import java.util.*
 
/**
 * created by zhang on 2017/12/20.
 */
class clockview(context: context?, attrs: attributeset? = null, defstyleattr: int = 0) : view(context, attrs, defstyleattr) {
 
  companion object {
    private const val default_width = 200 //默认宽度
  }
 
  private lateinit var mblackpaint: paint//黑色画笔
  private lateinit var mredpaint: paint //红色画笔
  private lateinit var mblackpaint2: paint//黑色画笔
  private lateinit var mtextpaint: paint
  private var hour: int? = null
  private var minute: int? = null
  private var second: int? = null
  private val textarray = arrayof("12", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11")
  private var refreshthread: thread? = null
  private var mhandler = @suppresslint("handlerleak")
  object : handler() {
    override fun handlemessage(msg: message?) {
      super.handlemessage(msg)
      when (msg?.what) {
        0 -> {
          invalidate()
        }
      }
 
    }
  }
 
  init {
    initpaints()
  }
 
  /**
   * 初始化画笔
   */
  private fun initpaints() {
    mblackpaint = paint()
    with(mblackpaint) {
      color = color.black
      strokewidth = 5f
      isantialias = true
      style = paint.style.stroke
    }
    //用于画表心
    mblackpaint2 = paint()
    with(mblackpaint2) {
      color = color.black
      isantialias = true
      style = paint.style.fill
    }
    mredpaint = paint()
    with(mredpaint) {
      color = color.red
      strokewidth = 5f
      isantialias = true
    }
 
    mtextpaint = paint()
    with(mtextpaint) {
      color = color.black
      textsize = 30f
      isantialias = true
    }
  }
 
  override fun ondraw(canvas: canvas?) {
    super.ondraw(canvas)
    //获取当前时间
    getcurrenttime()
 
    //先画最外层的圆圈
    drawoutercircle(canvas)
 
    //画刻度
    drawscale(canvas)
 
    //绘制文字
    drawtimetext(canvas)
 
    //绘制表针
    drawhand(canvas)
 
    //绘制表心
    drawcenter(canvas)
  }
 
  private fun getcurrenttime() {
    val calendar = calendar.getinstance()
    hour = calendar.get(calendar.hour)
    minute = calendar.get(calendar.minute)
    second = calendar.get(calendar.second)
  }
 
  private fun drawoutercircle(canvas: canvas?) {
    mblackpaint.strokewidth = 5f
    canvas?.drawcircle(measuredwidth / 2.tofloat(), measuredheight / 2.tofloat(), (measuredwidth / 2 - 5).tofloat(), mblackpaint)
  }
 
  private fun drawcenter(canvas: canvas?) {
    canvas?.drawcircle(measuredwidth / 2.tofloat(), measuredheight / 2.tofloat(), 20f, mblackpaint2)
  }
 
  private fun drawhand(canvas: canvas?) {
    drawsecond(canvas, mredpaint)
    mblackpaint.strokewidth = 10f
    drawminute(canvas, mblackpaint)
    mblackpaint.strokewidth = 15f
    drawhour(canvas, mblackpaint)
  }
 
  private fun drawtimetext(canvas: canvas?) {
    val textr = (measuredwidth / 2 - 50).tofloat()//文字构成的圆的半径
    for (i in 0..11) {
      //绘制文字的起始坐标
      val startx = (measuredwidth / 2 + textr * math.sin(math.pi / 6 * i) - mtextpaint.measuretext(textarray[i]) / 2).tofloat()
      val starty = (measuredheight / 2 - textr * math.cos(math.pi / 6 * i) + mtextpaint.measuretext(textarray[i]) / 2).tofloat()
      canvas?.drawtext(textarray[i], startx, starty, mtextpaint)
    }
  }
 
  private fun drawscale(canvas: canvas?) {
    var scalelength: float?
    canvas?.save()
    //0..59代表[0,59]
    for (i in 0..59) {
      if (i % 5 == 0) {
        //大刻度
        mblackpaint.strokewidth = 5f
        scalelength = 20f
      } else {
        //小刻度
        mblackpaint.strokewidth = 3f
        scalelength = 10f
      }
      canvas?.drawline(measuredwidth / 2.tofloat(), 5f, measuredwidth / 2.tofloat(), (5 + scalelength), mblackpaint)
      canvas?.rotate(360 / 60.tofloat(), measuredwidth / 2.tofloat(), measuredheight / 2.tofloat())
    }
    //恢复原来状态
    canvas?.restore()
  }
 
  /**
   * 绘制秒针
   */
  private fun drawsecond(canvas: canvas?, paint: paint?) {
    //秒针长半径 (表针会穿过表心 所以需要根据两个半径计算起始和结束半径)
    val longr = measuredwidth / 2 - 60
    val shortr = 60
    val startx = (measuredwidth / 2 - shortr * math.sin(second!!.times(math.pi / 30))).tofloat()
    val starty = (measuredwidth / 2 + shortr * math.cos(second!!.times(math.pi / 30))).tofloat()
    val endx = (measuredwidth / 2 + longr * math.sin(second!!.times(math.pi / 30))).tofloat()
    val endy = (measuredwidth / 2 - longr * math.cos(second!!.times(math.pi / 30))).tofloat()
    canvas?.drawline(startx, starty, endx, endy, paint)
  }
 
  /**
   * 绘制分针
   */
  private fun drawminute(canvas: canvas?, paint: paint?) {
    //半径比秒针小一点
    val longr = measuredwidth / 2 - 90
    val shortr = 50
    val startx = (measuredwidth / 2 - shortr * math.sin(minute!!.times(math.pi / 30))).tofloat()
    val starty = (measuredwidth / 2 + shortr * math.cos(minute!!.times(math.pi / 30))).tofloat()
    val endx = (measuredwidth / 2 + longr * math.sin(minute!!.times(math.pi / 30))).tofloat()
    val endy = (measuredwidth / 2 - longr * math.cos(minute!!.times(math.pi / 30))).tofloat()
    canvas?.drawline(startx, starty, endx, endy, paint)
  }
 
 
  /**
   * 绘制时针
   */
  private fun drawhour(canvas: canvas?, paint: paint?) {
    //半径比秒针小一点
    val longr = measuredwidth / 2 - 120
    val shortr = 40
    val startx = (measuredwidth / 2 - shortr * math.sin(hour!!.times(math.pi / 6))).tofloat()
    val starty = (measuredwidth / 2 + shortr * math.cos(hour!!.times(math.pi / 6))).tofloat()
    val endx = (measuredwidth / 2 + longr * math.sin(hour!!.times(math.pi / 6))).tofloat()
    val endy = (measuredwidth / 2 - longr * math.cos(hour!!.times(math.pi / 6))).tofloat()
    canvas?.drawline(startx, starty, endx, endy, paint)
  }
 
  /**
   * 进行测量
   */
  override fun onmeasure(widthmeasurespec: int, heightmeasurespec: int) {
    super.onmeasure(widthmeasurespec, heightmeasurespec)
    val widthspecmode = measurespec.getmode(widthmeasurespec)
    val widthspecsize = measurespec.getsize(widthmeasurespec)
    val heightspecmode = measurespec.getmode(heightmeasurespec)
    val heightspecsize = measurespec.getsize(heightmeasurespec)
    val result = if (widthspecmode == measurespec.at_most && heightspecmode == measurespec.at_most) {
      default_width
    } else {
      math.min(widthspecsize, heightspecsize)
    }
 
    setmeasureddimension(result, result)
  }
 
  override fun onattachedtowindow() {
    super.onattachedtowindow()
    //启动线程 刷新界面
    refreshthread = thread(runnable {
      while (true) {
        try {
          thread.sleep(1000)
          mhandler.sendemptymessage(0)
        } catch (e: interruptedexception) {
          break
        }
      }
    })
    refreshthread?.start()
  }
 
  override fun ondetachedfromwindow() {
    super.ondetachedfromwindow()
    mhandler.removecallbacksandmessages(null)
    //中断线程
    refreshthread?.interrupt()
  }
}

在这送上几点建议,1.尽量不要再ondraw里面创建对象,因为view可能会多次重绘,每次都创建新的对象会造成不必要的内存浪费

2.onmeasure方法会调用多次,请保证你的逻辑覆盖性,否则可能会出现没有按照你的预期得到宽高

3.线程的谨慎使用

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。