Android自定义view仿QQ的Tab按钮动效

话不多说 先上效果图

实现其实很简单,先用两张图

一张是背景的图,一张是笑脸的图片,笑脸的图片是白色,可能看不出来。实现思路:主要是再触摸view的时候同时移动这两个图片,但是移动的距离不一样,造成的错位感,代码很简单:

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.example.dawnmvvm.R
import com.example.dawnmvvm.util.LogUtil

class MyDrawBitmap @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : View(context, attrs, defStyleAttr, defStyleRes) {
    private var dx = 0f
    private var dy = 0f
    private var dx1 =0f
    private var dy1 = 0f
    private val bitmap: Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.drawable.bg_tab);//背景
    }
    private val bitmap2: Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.drawable.img_smile);//笑脸
    }

    override fun draw(canvas: Canvas?) {
        super.draw(canvas)

        LogUtil.e("MyDrawBitmap===x===${dx}")
        LogUtil.e("MyDrawBitmap===y===${dy}")
        if(dx<0){
            dx=0f
        }
        if(dy<0){
            dy=0f;
        }

        canvas?.drawBitmap(bitmap, dx, dy, null);//移动背景
        canvas?.drawBitmap(bitmap2, dx1, dy1, null);//移动笑脸
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {

        when (event.action) {

            MotionEvent.ACTION_UP-> {

                dx = 0f
                dy = 0f
                dx1 = 0f
                dy1 = 0f
            }
            else->{
                dx = event.x/20f
                dy = event.y/20f
                dx1 = event.x/10f
                dy1 = event.y/10f
            }

        }
        invalidate()

        return true;
    }


}

是不是很简单,不过不是很完美

猜你喜欢

转载自blog.csdn.net/w_1220577523/article/details/112991000