自定义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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355

推荐阅读更多精彩内容