自定义view--双击点赞

实现效果如下:
1607330762041.gif

三阶贝塞尔曲线
cubicTo(控制点1x坐标,控制点1y坐标,控制点2x坐标,控制点2y坐标,终点x坐标,终点y坐标)

实现控件分为两部分

  • 心形控件-自定义view
  • 存放心形控件的容器 - 自定义ViewGroup

1. 心形控件(可以使用ImageView代替)

因为正在学习自定义view的知识,尽量不适用图片资源。而且画爱心图案需要用到三阶贝塞尔曲线,正好练习

class HeartView : View {
    private var radius = 0f
    val paint = Paint() // 画笔
    private val pointStart = PointF() // 画心需要三阶贝塞尔曲线,是path的起点
    private val point1 = PointF() // 控制点1
    private val point2 = PointF() // 控制点2
    private val pointEnd = PointF() // 终点

    // 右半边心的两个控制点
    private val point1Right = PointF() // 控制点1
    private val point2Right = PointF() // 控制点2
    val path = Path()
    // HeartView的中心点
    // downX 、downY 名称起得不好
    private var downX = 0f
    private var downY = 0f
    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        paint.apply {
            isAntiAlias = true
            color = Color.RED
        }
//        setBackgroundColor(Color.BLACK)
    }

   

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        /**
          * 此处测量实现的效果是
          * 1. 当宽高都为wrap_content时,宽高都设置为240px
          * 2. 当宽或高有一个为wrap_content ,另一个为具体值时,比较具体值和240px的大小,取较小值
          * 3. 当都为具体值时,比较大小,取小值
        **/
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var width = MeasureSpec.getSize(widthMeasureSpec)
        var height = MeasureSpec.getSize(heightMeasureSpec)

        if (widthMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.AT_MOST) {
            if (widthMode == MeasureSpec.AT_MOST) {
                width = getSmallSize(240,height)
            }
            if (heightMode == MeasureSpec.AT_MOST) {
                height = getSmallSize(width,240)
            }
            setMeasuredDimension(width,height)
        }else {
            val size = getSmallSize(width,height)
            setMeasuredDimension(size,size)
        }

    }
    // 比较两个参数的大小,返回较小的值
    private fun getSmallSize(width:Int, height:Int):Int{
        return if (width > height) {
            height
        } else {
            width
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        Log.e("宽","$measuredWidth")
        Log.e("高","$measuredHeight")
        // 此处radius是控件中心点到贝塞尔曲线控制点的计算尺度
        // 可以随意指定,不用计较具体的计算方法,这里是试出来的
        // 这样画出来的爱心比较好看
        radius = measuredHeight/2.6f
        val xinR = measuredHeight/1.5f
        val xinR2 = measuredHeight / 2.4f
        downX = measuredWidth/2f
        downY = measuredHeight/2f
        canvas.apply {
            if (downX == 0f) {
                return
            }

            // 画左半边的心
            pointStart.x = downX
            pointStart.y = (downY - radius)

            point1.x = pointStart.x - xinR
            point1.y = pointStart.y - xinR2

            point2.x = pointStart.x - xinR
            point2.y = pointStart.y + xinR2 / 5 * 6


            pointEnd.x = downX
            pointEnd.y = (downY + radius)
            path.moveTo(pointStart.x, pointStart.y)
            path.cubicTo(
                point1.x,
                point1.y,
                point2.x,
                point2.y,
                pointEnd.x,
                pointEnd.y
            )

            // 画右半边的心
            point1Right.x = pointStart.x + xinR
            point1Right.y = pointStart.y + xinR2 / 5 * 6
            point2Right.x = pointStart.x + xinR
            point2Right.y = pointStart.y - xinR2

            path.cubicTo(
                point1Right.x,
                point1Right.y,
                point2Right.x,
                point2Right.y,
                pointStart.x,
                pointStart.y
            )
            drawPath(path, paint)
            path.close()
            path.reset()
        }
    }
}

需要注意的地方

  • 最开始画爱心的方案是先画左边半块,然后通过moveTo移动path的起始点,再画右边半块,左边和右边分别是一个三阶贝塞尔曲线,这样画出的爱心中间有一条缝隙,就算起点和终点一样也还是存在
  • 现在的方案是一笔画下来,最后调用一次drawPath(),中间不调用moveTo()。
    这样的话,画右边的贝塞尔曲线时,起点和终点是反着的,控制点1和控制点2也要调换位置

2. 存放心形控件,响应双击事件的容器

class DianZanView : RelativeLayout {
    var gestureDetector: GestureDetector
    val listHeart = mutableListOf<HeartView>()

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        gestureDetector =
            GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
                override fun onDoubleTap(e: MotionEvent): Boolean {
                    // 处理双击事件
                    // 在点击位置生成一个心图案
                    val heartView = HeartView(context, e.x, e.y).apply {

//                        layoutParams = LayoutParams(320, 1040)
                        layoutParams =
                            LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
                        visibility = INVISIBLE // 因为要知道控件本身的宽高,来计算他的坐标,所以必须在能看到它时,设置它的x,y
                        // 但是这样,在一开始的坐标会显示在左上角,闪一下,再出现在给定坐标位置,所以先隐藏
                        // 等能看到时,在显示
                        post {
                            x = e.x - measuredWidth / 2 // 设置heartView的x轴坐标
                            y = e.y - measuredHeight / 2 // 设置heartView的Y轴坐标
                            // 在heartView可见时,开启动画
                            startUpAnimator(this) // 向上移动的路径是一个三阶贝塞尔曲线
//                            startUpAlphaZoomAnimator(this) // 向上平移,放大,透明度变化
                            visibility = VISIBLE
                        }
                    }

                    addView(heartView)
                    listHeart.add(heartView)
                    invalidate()
                    return super.onDoubleTap(e)
                }
            })
    }

    // 开启动画,向上移动,轨迹是一个三阶贝塞尔曲线,伴随透明度变化
    private fun startUpAnimator(view: HeartView) {
        // 创建移动的路径,一个贝塞尔曲线
        val path = Path()
        path.moveTo(view.x,view.y)
        path.cubicTo(view.x- measuredWidth/3,view.y- measuredHeight/3,view.x+measuredWidth/3,view.y-measuredHeight/2,view.x,0f)
        val pathMeasure = PathMeasure(path,false)
        val pathLength = pathMeasure.length

        val pathAnim = ValueAnimator.ofInt(1,pathLength.toInt()).apply {
            addUpdateListener {
                val value = it.animatedValue as Int
                val xy = FloatArray(2)
                val aa = FloatArray(2)
                // 执行完毕,xy即为横纵坐标
                pathMeasure.getPosTan(value.toFloat(), xy, aa)
                view.x = xy[0]
                view.y = xy[1]
                invalidate()
            }
        }

        val alphaAnim = ValueAnimator.ofFloat(1f, 0f).apply {

            addUpdateListener {
                val value = it.animatedValue as Float
                var alpha = value
                if (alpha <= 0) {
                    alpha = 0f
                }
                view.alpha = alpha
                invalidate()
            }
        }

        AnimatorSet().apply {
            duration = 1000
            playTogether(pathAnim,alphaAnim)
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    super.onAnimationEnd(animation)
                    this@DianZanView.removeView(view)

                }
            })
            start()
        }
    }

    // 向上,放大,透明
    private fun startUpAlphaZoomAnimator(view: HeartView) {
        view.translationY
        view.scaleX
        val targetY = view.y
        val upAnimator = ObjectAnimator.ofFloat(view,"translationY",targetY,targetY-measuredHeight/5)
        val scaleXAnimator = ObjectAnimator.ofFloat(view,"scaleX",1f,2f)
        val scaleYAnimator = ObjectAnimator.ofFloat(view,"scaleY",1f,2f)
        val alphaAnimator = ObjectAnimator.ofFloat(view,"alpha",1f,0f)

        AnimatorSet().apply {
            playTogether(upAnimator,scaleXAnimator,scaleYAnimator,alphaAnimator)
            duration = 1000
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    super.onAnimationEnd(animation)
                    this@DianZanView.removeView(view)
                    Log.e("DianZanView","子view数量为:${this@DianZanView.childCount}")
                }
            })
            start()
        }

    }
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(ev: MotionEvent): Boolean {
        gestureDetector.onTouchEvent(ev)
        return super.onTouchEvent(ev)
    }
}

实现思路:
监听双击事件,用户双击时,创建一个HeartView,在HeratView可见时,设置它的坐标(双击的位置),并开启动画。
在设置HeartView坐标时,需要减去HeartView自身的宽高,所以需要HeartView.post{} 在内部设置x,y

更新:新增按照路径移动的动画,同时伴随透明度变化

效果如下:
1607414741725[1].gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容