L-release-like Touch Ripple animation on pre-L

前端 未结 2 1864
礼貌的吻别
礼貌的吻别 2021-01-30 14:58

I love the new Touch Ripple animation that was introduced in the new Android L-release as part of the new UI philosophy Material Design.

You can find a video of it in th

2条回答
  •  名媛妹妹
    2021-01-30 15:49

    Something I cooked up quickly, far from ideal, but hey, it's something: Gist

    Basically drawing a circle based on an animated radius. To get the exact L-effect, some more tweaking should be done. The interesting code:

    @Override
    public boolean onTouchEvent(@NonNull final MotionEvent event) {
        if (event.getActionMasked() == MotionEvent.ACTION_UP) {
            mDownX = event.getX();
            mDownY = event.getY();
    
            ObjectAnimator animator = ObjectAnimator.ofFloat(this, "radius", 0, getWidth() * 3.0f);
            animator.setInterpolator(new AccelerateInterpolator());
            animator.setDuration(400);
            animator.start();
        }
        return super.onTouchEvent(event);
    }
    
    public void setRadius(final float radius) {
        mRadius = radius;
        if (mRadius > 0) {
            RadialGradient radialGradient = new RadialGradient(
                    mDownX,
                    mDownY,
                    mRadius * 3,
                    Color.TRANSPARENT,
                    Color.BLACK,
                    Shader.TileMode.MIRROR
            );
            mPaint.setShader(radialGradient);
        }
        invalidate();
    }
    
    private Path mPath = new Path();
    private Path mPath2 = new Path();
    
    @Override
    protected void onDraw(@NonNull final Canvas canvas) {
        super.onDraw(canvas);
    
        mPath2.reset();
        mPath2.addCircle(mDownX, mDownY, mRadius, Path.Direction.CW);
    
        canvas.clipPath(mPath2);
    
        mPath.reset();
        mPath.addCircle(mDownX, mDownY, mRadius / 3, Path.Direction.CW);
    
        canvas.clipPath(mPath, Region.Op.DIFFERENCE);
    
        canvas.drawCircle(mDownX, mDownY, mRadius, mPaint);
    }
    

    In their talk "What's new in Android", they talked about that this animation actually happens on a separate "Render thread", which will make its debut in the L-release. This will allow smoother animations, even when the UI thread is busy inflating, or doing anything else expensive.

提交回复
热议问题