Android 特效之炫酷水波纹动画

效果图


Android 特效之炫酷水波纹动画_第1张图片

示例代码

1.初始化画笔

 public WaveView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPath = new Path();
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#FF2877DD"));
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        //随波摇的头像
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.love, options);
    }

 

2.绘制水波纹

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();
        int halfWaveLen = mItemWaveLength / 2;
        mPath.moveTo(-mItemWaveLength + dx, originY);
        int i = -mItemWaveLength;
        for (; i <= getWidth() + mItemWaveLength; i += mItemWaveLength) {
            mPath.rQuadTo(halfWaveLen / 2, -100, halfWaveLen, 0);
            mPath.rQuadTo(halfWaveLen / 2, 100, halfWaveLen, 0);
        }
        mPath.lineTo(getWidth(), getHeight());
        mPath.lineTo(0, getHeight());
        mPath.close();

        canvas.drawPath(mPath, mPaint);

        mRegion = new Region();
        float left = getWidth() / 2;

        Region clip = new Region((int) (left - 0.01), 0, (int) left, getHeight() * 2);
        mRegion.setPath(mPath, clip);

        Rect bounds = mRegion.getBounds();
        canvas.drawBitmap(mBitmap, bounds.left - mBitmap.getWidth() / 2, bounds.top - mBitmap.getHeight(), mPaint);

    }

3.开启动画实现平移

 public void startAnim() {
        animator = ValueAnimator.ofInt(0, mItemWaveLength);
        animator.setDuration(2800);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                dx = (int) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        animator.start();

    }

 

你可能感兴趣的:(Android 特效之炫酷水波纹动画)