天天看點

水波紋效果

項目中需要使用到的水波紋效果,效果圖如下:

水波紋效果

代碼如下:

/**
 * Created by csc on 2018/6/7.
 * information:使用貝塞爾曲線(二階)實作水波紋效果
 */

class WaveView(context: Context) : View(context) {

    lateinit var mPaint: Paint
    lateinit var mPath: Path

    //一條波紋的長度
    val mWL = 1000

    //波紋的個數
    var mWaveCount: Int? = null

    //偏移量
    var offset: Int? = null
   
    //View的寬度
    var mViewWidth: Int? = null
    //View的寬度
    var mViewHeight: Int? = null

    //View高度的一半
    var mViewHalfHeight: Int? = null


    constructor(context: Context,attrs: AttributeSet): this(context) {
        //初始化畫筆
        initPaint()
        //初始化動畫
        initAnimator()
    }

    //初始化畫筆
    private fun initPaint() {
        mPath = Path()
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mPaint.color = Color.WHITE
        mPaint.style = Paint.Style.FILL_AND_STROKE
        mPaint.alpha = 60

    }

    //初始化動畫
    private fun initAnimator() {
        var animator: ValueAnimator = ValueAnimator.ofInt(0, mWL)
        animator.setDuration(2000)
        animator.repeatCount = ValueAnimator.INFINITE
        animator.interpolator = LinearInterpolator()
        animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
            override fun onAnimationUpdate(animation: ValueAnimator?) {
                offset = animation?.getAnimatedValue() as Int

                postInvalidate()
            }
        })
        animator.start()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        mViewWidth = w
        mViewHeight = h

        //獲得波紋的數量
        mWaveCount = Math.round(mViewWidth!! / mWL + 1.5).toInt()

        //View高度的一半
        mViewHalfHeight = mViewHeight!! / 2

    }

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

        mPath.reset()
        mPath.moveTo(-(mWL + offset!!).toFloat(), mViewHalfHeight?.toFloat()!!)
     
        for (i in 0 until mWaveCount!!) {
            mPath.quadTo(((-mWL * 3 / 4) + (i * mWL)).toFloat() + offset!!, (mViewHalfHeight!! + 60).toFloat(), ((-mWL / 2) + (i * mWL) + offset!!).toFloat(), mViewHalfHeight!!.toFloat())
            mPath.quadTo(((-mWL / 4) + (i * mWL)).toFloat() + offset!!, (mViewHalfHeight!! - 60).toFloat(), (i * mWL + offset!!).toFloat(), mViewHalfHeight!!.toFloat())
        }

        mPath.lineTo(mViewWidth!!.toFloat(), mViewHeight!!.toFloat())
        mPath.lineTo(0.0F, mViewHeight!!.toFloat())

        mPath.close()
       
        canvas?.drawPath(mPath, mPaint)
        
    }
}
           

就這樣搞定,是不是很簡單.

繼續閱讀