美文网首页
Android自定义View(12) 《实现一个带动画的单选框》

Android自定义View(12) 《实现一个带动画的单选框》

作者: 非典型程序猿 | 来源:发表于2021-09-11 00:30 被阅读0次

    概述

    今天无意发现MIUI的一个单选框,发现还挺好玩的,就抽空写了一下,单选框具体是长这个样子的

    效果

    chek_view.gif

    绘制的图形

    整体上绘制图形分为3个部分

    • 1.带阴影的未选中状态的圆形背景
    • 2.带阴影的选中状态的选中状态的圆形背景
    • 3.绘制中间的勾形路径

    用到的动画

    首先我们考虑把动画分为2部分,第一部分为手指按下去的事件,此时开始进行手指按下去的动画,当松开手指时我们开始执行松开手指的动画。
    如果没有通过本身点击事件触发,我们则先播放按下去的动画,然后监听动画结束再播放松开手指的动画

    先上代码

    package com.tx.txcustomview.view
    
    import android.animation.Animator
    import android.animation.ValueAnimator
    import android.content.Context
    import android.graphics.*
    import android.util.AttributeSet
    import android.util.Log
    import android.view.MotionEvent
    import android.view.View
    
    
    /**
     * create by xu.tian
     * @date 2021/9/10
     */
    class CheckView(context: Context?, attrs: AttributeSet?) : View(context, attrs){
        // 当前选中状态
        var checked = false
        // 创建画笔对象
        var paint = Paint()
        // 圆心x坐标
        var centerX = 0f
        // 圆心y坐标
        var centerY = 0f
        // 圆半径
        var radius = 0f
        // 实际绘制的真实圆半径
        var drawRadius = 0f
    
        // 按下去执行的动画
        lateinit var pressAnimator: ValueAnimator
        // 按下去动画执行的时间
        var pressAnimDuration = 100L
        // 当前的按下去的动画值0~100
        var pressCurrentValue = 0F
        // 按下去时的缩放值
        var pressScale = 0.8f
        
        // 松手执行的动画
        lateinit var upAnimator : ValueAnimator
        // 松手动画执行的时间
        var upAnimDuration = 300L
        // 当前的松手的动画值0~100
        var upCurrentValue = 0F
        // 判断是否是外部设置
        var isSet = false
    
        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            setLayerType(LAYER_TYPE_SOFTWARE,paint)
            if (!checked){
                drawUnchecked(canvas)
            }else{
                drawChecked(canvas)
            }
        }
    
        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            super.onSizeChanged(w, h, oldw, oldh)
            this.centerX = (w/2).toFloat()
            this.centerY = (h/2).toFloat()
            this.radius = centerX*9/10
            this.drawRadius = radius
            initPressAnimator()
            initUpAnimator()
        }
    
        override fun onTouchEvent(event: MotionEvent?): Boolean {
            when(event?.action){
                MotionEvent.ACTION_DOWN -> actionPress()
                MotionEvent.ACTION_UP -> actionUp()
            }
            return true
        }
    
        private fun initPressAnimator(){
            pressAnimator = ValueAnimator.ofFloat(0f,100f)
            pressAnimator.duration = pressAnimDuration
            pressAnimator.addUpdateListener { valueAnimator ->
                pressCurrentValue = valueAnimator.animatedValue as Float
                drawRadius = radius*(1-(pressCurrentValue/100)*(1-pressScale))
                postInvalidate()
            }
            pressAnimator.addListener(object : Animator.AnimatorListener{
                override fun onAnimationStart(p0: Animator?) {
    
                }
    
                override fun onAnimationEnd(p0: Animator?) {
                    Log.d("CheckView", "pressAnimator onAnimationEnd --->$pressCurrentValue")
                    if (isSet){
                        upAnimator.start()
                    }
                }
    
                override fun onAnimationCancel(p0: Animator?) {
    
                }
    
                override fun onAnimationRepeat(p0: Animator?) {
    
                }
            })
    
        }
        private fun initUpAnimator(){
            upAnimator = ValueAnimator.ofFloat(0f,100f)
            upAnimator.duration = upAnimDuration
            upAnimator.addUpdateListener { valueAnimator ->
                upCurrentValue = valueAnimator.animatedValue as Float
                drawRadius = radius*pressScale+(1-pressScale)*(upCurrentValue/100)*radius
                postInvalidate()
            }
            upAnimator.addListener(object : Animator.AnimatorListener{
                override fun onAnimationStart(p0: Animator?) {
                }
    
                override fun onAnimationEnd(p0: Animator?) {
                    if (!checked){
                        pressCurrentValue = 0f
                        upCurrentValue = 0f
                    }else{
                        pressCurrentValue = 100f
                        upCurrentValue = 100f
                    }
                    upAnimator.cancel()
                    Log.d("CheckView", "upAnimator onAnimationEnd --->$upCurrentValue")
                }
    
                override fun onAnimationCancel(p0: Animator?) {
    
                }
    
                override fun onAnimationRepeat(p0: Animator?) {
    
                }
            })
    
        }
    
        private fun actionPress(){
            isSet = false
            pressAnimator.start()
        }
    
        private fun actionUp() {
            checked = !checked
            upAnimator.start()
        }
    
        private fun drawChecked(canvas: Canvas){
            // 绘制选中时的圆形背景
            paint.color = Color.BLUE
            paint.style = Paint.Style.FILL
            canvas.drawCircle(centerX,centerY,drawRadius,paint)
            // 绘制中间的勾
            var path = Path()
            path.moveTo(centerX-drawRadius/2,centerY-drawRadius/10);
            path.lineTo(centerX-drawRadius/15,centerY+drawRadius/3);
            path.lineTo(centerX+drawRadius/2,centerY-drawRadius/3);
            var dstPah = Path()
            var pathMeasure = PathMeasure()
            pathMeasure.setPath(path,false)
            pathMeasure.getSegment(0f,pathMeasure.length*(upCurrentValue/100),dstPah,true)
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = drawRadius / 6
            paint.color = Color.WHITE
            paint.strokeCap = Paint.Cap.ROUND
            paint.strokeJoin = Paint.Join.ROUND
            canvas.drawPath(dstPah,paint)
        }
    
        private fun drawUnchecked(canvas: Canvas){
            // 绘制未选中状态的背景
            paint.style = Paint.Style.FILL
            paint.color = Color.GRAY
            paint.setShadowLayer(5f,5f,5f,Color.parseColor("#4D000000"))
            paint.alpha = 150
            canvas.drawCircle(centerX,centerY,drawRadius,paint)
        }
    
        fun setStatusChecked(checked : Boolean){
            this.checked  = checked
            isSet = true
            pressAnimator.start()
        }
        override fun onDetachedFromWindow() {
            super.onDetachedFromWindow()
            pressAnimator.cancel()
            upAnimator.cancel()
        }
    }
    

    思路

    我们利用两个ValueAnimator来控制动画进行中我们绘制的背景的半径以及画笔的粗细等,我们先确认在绘制过程中哪些值需要变化

    • 绘制的背景的半径
      因为这里我们使用的勾形路径和画笔宽度都是根据半径决定的,所以我们只需要在动画变化的过程中确认好半径大小就没问题了。我们每次在按下去的时候相当于缩放,然后在松开手指的时候切换状态并播放动画

    核心代码

    这里我们只看最重要的绘制部分以及使用动画值的部分
    首先是绘制未选中状态圆形的背景的代码

    private fun drawUnchecked(canvas: Canvas){
            // 绘制未选中状态的背景
            paint.style = Paint.Style.FILL
            paint.color = Color.GRAY
            paint.setShadowLayer(5f,5f,5f,Color.parseColor("#4D000000"))
            paint.alpha = 150
            canvas.drawCircle(centerX,centerY,drawRadius,paint)
        }
    

    这里的drawRadius是我们实际画的圆的半径
    其次是选中状态的图形

     private fun drawChecked(canvas: Canvas){
            // 绘制选中时的圆形背景
            paint.color = Color.BLUE
            paint.style = Paint.Style.FILL
            canvas.drawCircle(centerX,centerY,drawRadius,paint)
            // 绘制中间的勾
            var path = Path()
            path.moveTo(centerX-drawRadius/2,centerY-drawRadius/10);
            path.lineTo(centerX-drawRadius/15,centerY+drawRadius/3);
            path.lineTo(centerX+drawRadius/2,centerY-drawRadius/3);
            var dstPah = Path()
            var pathMeasure = PathMeasure()
            pathMeasure.setPath(path,false)
            pathMeasure.getSegment(0f,pathMeasure.length*(upCurrentValue/100),dstPah,true)
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = drawRadius / 6
            paint.color = Color.WHITE
            paint.strokeCap = Paint.Cap.ROUND
            paint.strokeJoin = Paint.Join.ROUND
            canvas.drawPath(dstPah,paint)
        }
    

    这个勾的坐标是真的难画,和UI小姐姐看了iconfont的几个图标才找来了灵感画出了这个看起来还不错的~
    其次是按下去的动画的部分

     private fun initPressAnimator(){
            pressAnimator = ValueAnimator.ofFloat(0f,100f)
            pressAnimator.duration = pressAnimDuration
            pressAnimator.addUpdateListener { valueAnimator ->
                pressCurrentValue = valueAnimator.animatedValue as Float
                drawRadius = radius*(1-(pressCurrentValue/100)*(1-pressScale))
                postInvalidate()
            }
            pressAnimator.addListener(object : Animator.AnimatorListener{
                override fun onAnimationStart(p0: Animator?) {
    
                }
    
                override fun onAnimationEnd(p0: Animator?) {
                    Log.d("CheckView", "pressAnimator onAnimationEnd --->$pressCurrentValue")
                    if (isSet){
                        upAnimator.start()
                    }
                }
    
                override fun onAnimationCancel(p0: Animator?) {
    
                }
    
                override fun onAnimationRepeat(p0: Animator?) {
    
                }
            })
        }
    

    注意这里的drawRaidus的计算公式

    drawRadius = radius*(1-(pressCurrentValue/100)*(1-pressScale))
    

    在动画值从0~100的过程中,drawRadius最终会变成我们所需要的缩放后的值
    然后是松开手的动画

      private fun initUpAnimator(){
            upAnimator = ValueAnimator.ofFloat(0f,100f)
            upAnimator.duration = upAnimDuration
            upAnimator.addUpdateListener { valueAnimator ->
                upCurrentValue = valueAnimator.animatedValue as Float
                drawRadius = radius*pressScale+(1-pressScale)*(upCurrentValue/100)*radius
                postInvalidate()
            }
            upAnimator.addListener(object : Animator.AnimatorListener{
                override fun onAnimationStart(p0: Animator?) {
                }
    
                override fun onAnimationEnd(p0: Animator?) {
                    if (!checked){
                        pressCurrentValue = 0f
                        upCurrentValue = 0f
                    }else{
                        pressCurrentValue = 100f
                        upCurrentValue = 100f
                    }
                    upAnimator.cancel()
                    Log.d("CheckView", "upAnimator onAnimationEnd --->$upCurrentValue")
                }
    
                override fun onAnimationCancel(p0: Animator?) {
    
                }
    
                override fun onAnimationRepeat(p0: Animator?) {
    
                }
            })
    }
    

    这里其实也只是计算了一下drawRadius的值

    drawRadius = radius*pressScale+(1-pressScale)*(upCurrentValue/100)*radius
    

    这个和按下去就是反过来的,从缩放后的值逐渐变到原来的大小,最后记得执行完两个动画后把状态值重置~

    总结

    整体来说是比较简单的一个控件,但是如果需要更细致的状态切换那么还是需要再下点功夫的~
    See you ~

    相关文章

      网友评论

          本文标题:Android自定义View(12) 《实现一个带动画的单选框》

          本文链接:https://www.haomeiwen.com/subject/ugrowltx.html