Android custom view for bubble animation

Time:2021-10-19

This example shares the specific code of Android custom view to realize bubble animation for your reference. The specific contents are as follows

1、 Foreword

Recently, there is a need to make a bubble animation of a kettle. First, I searched the Internet and found an article: Android realizes bubble animation

After testing, it is found that if it is used as a sub view, the small ball will overflow the boundary. So I made a simple modification.

2、 Code

1. Randomly moving bubbles

Ball class

/**
 * @author jiang yuhang
 * @date 2021-04-18 19:57
 */
class Ball {
    //Radius
    @kotlin.jvm.JvmField
    var radius = 0

    //Center of circle
    @kotlin.jvm.JvmField
    var cx = 0f

    //Center of circle
    @kotlin.jvm.JvmField
    var cy = 0f

    //X-axis speed
    @kotlin.jvm.JvmField
    var vx = 0f

    //Y-axis speed
    @kotlin.jvm.JvmField
    var vy = 0f

    @kotlin.jvm.JvmField
    var paint: Paint? = null

    //Move
    fun move() {
        //Move in the direction of the angle to offset the center of the circle
        cx += vx
        cy += vy
    }

    fun left(): Int {
        return (cx - radius).toInt()
    }

    fun right(): Int {
        return (cx + radius).toInt()
    }

    fun bottom(): Int {
        return (cy + radius).toInt()
    }

    fun top(): Int {
        return (cy - radius).toInt()
    }
}

Ballview class

/**
 * @author jiang yuhang
 * @date 2021-04-18 19:53
 */
public class BallView extends View {
    private final Random mRandom;
    private final int mCount = 5;   //  Number of small balls
    private final int minSpeed = 5; //  Minimum moving speed of small ball
    private final int maxSpeed = 20; //  Maximum movement speed of small ball

    public Ball[] mBalls;   //  An array that holds all the balls
    private int maxRadius;  //  Maximum radius of small ball
    private int minRadius; //  Minimum radius of small ball
    private int mWidth = 200;
    private int mHeight = 200;

    public BallView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        //Initialize all balls (set colors and brushes, initialize the angle of movement)
        this.mRandom = new Random();
        final RandomColor randomColor = new RandomColor(); //  Randomly generate good-looking colors, GitHub open source library.
        this.mBalls = new Ball[this.mCount];

        for (int i = 0; i < this.mCount; i++) {
            this.mBalls[i] = new Ball();
            //Set brush
            final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(randomColor.randomColor());
            paint.setStyle(Paint.Style.FILL);
            paint.setAlpha(180);
            paint.setStrokeWidth(0);

            //Set speed
            final float speedX = (this.mRandom.nextInt(this.maxSpeed - this.minSpeed + 1) + 5) / 10f;
            final float speedY = (this.mRandom.nextInt(this.maxSpeed - this.minSpeed + 1) + 5) / 10f;
            this.mBalls[i].paint = paint;
            this.mBalls[i].vx = this.mRandom.nextBoolean() ? speedX : -speedX;
            this.mBalls[i].vy = this.mRandom.nextBoolean() ? speedY : -speedY;
        }
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        this.mWidth = View.resolveSize(this.mWidth, widthMeasureSpec);
        this.mHeight = View.resolveSize(this.mHeight, heightMeasureSpec);
        this.setMeasuredDimension(this.mWidth, this.mHeight);
        this.maxRadius = this.mWidth / 12;
        this.minRadius = this.maxRadius / 2;

        //Initializes the radius and center of a circle
        for (Ball mBall : this.mBalls) {
            mBall.radius = this.mRandom.nextInt(this.maxRadius + 1 - this.minRadius) + this.minRadius;
            //Initialize the position of the center of the circle. The minimum x is radius and the maximum is mwidth radius
            mBall.cx = this.mRandom.nextInt(this.mWidth - mBall.radius) + mBall.radius;
            mBall.cy = this.mRandom.nextInt(this.mHeight - mBall.radius) + mBall.radius;
        }
    }

    @Override
    protected void onDraw(final Canvas canvas) {
        final long startTime = System.currentTimeMillis();
        //Draw all the circles first
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            canvas.drawCircle(ball.cx, ball.cy, ball.radius, ball.paint);
        }

        //Ball collision boundary
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            this.collisionDetectingAndChangeSpeed(ball); //  Calculation of collision boundary
            ball.move(); //  move
        }

        final long stopTime = System.currentTimeMillis();
        final long runTime = stopTime - startTime;
        //Once every 16 milliseconds
        this.postInvalidateDelayed(Math.abs(runTime - 16));
    }

    //Judge whether the ball collides with the collision boundary
    public void collisionDetectingAndChangeSpeed(final Ball ball) {
        final int left = 0;
        final int top = 0;
        final int right = this.mWidth;
        final int bottom = this.mHeight;

        final float speedX = ball.vx;
        final float speedY = ball.vy;

        //The velocity of X is reversed around the collision. The judgment of speed is to prevent repeated collision detection, and then stick it to the wall ==
        if (ball.left() <= left && speedX < 0) {
            ball.vx = -ball.vx;
        } else if (ball.top() <= top && speedY < 0) {
            ball.vy = -ball.vy;
        } else if (ball.right() >= right && speedX > 0) {
            ball.vx = -ball.vx;
        } else if (ball.bottom() >= bottom && speedY > 0) {
            ball.vy = -ball.vy;
        }
    }
}

2. Hot water bubble

/**
 * @author jiang yuhang
 * @date 2021-04-18 19:57
 */
class Ball {
    //Radius
    @kotlin.jvm.JvmField
    var radius = 0

    //Center of circle
    @kotlin.jvm.JvmField
    var cx = 0f

    //Center of circle
    @kotlin.jvm.JvmField
    var cy = 0f

    //X-axis speed
    @kotlin.jvm.JvmField
    var vx = 0f

    //Y-axis speed
    @kotlin.jvm.JvmField
    var vy = 0f

    @kotlin.jvm.JvmField
    var paint: Paint? = null

    //Move
    fun move() {
        //Move in the direction of the angle to offset the center of the circle
        cx += vx
        cy += vy
    }

    fun left(): Int {
        return (cx - radius).toInt()
    }

    fun right(): Int {
        return (cx + radius).toInt()
    }

    fun bottom(): Int {
        return (cy + radius).toInt()
    }

    fun top(): Int {
        return (cy - radius).toInt()
    }
}
/**
 * @author jiang yuhang
 * @date 2021-04-18 19:53
 */
public class BallView extends View {
    final RandomColor randomColor = new RandomColor(); //  Randomly generate good-looking colors, GitHub open source library.
    private final Random mRandom = new Random();
    private final int mCount = 5;   //  Number of small balls
    private final int minSpeed = 5; //  Minimum moving speed of small ball
    private final int maxSpeed = 15; //  Maximum movement speed of small ball
    public Ball[] mBalls = new Ball[this.mCount];   //  An array that holds all the balls
    private int maxRadius;  //  Maximum radius of small ball
    private int minRadius; //  Minimum radius of small ball
    private int mWidth = 200;
    private int mHeight = 200;


    public BallView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        this.mWidth = View.resolveSize(this.mWidth, widthMeasureSpec);
        this.mHeight = View.resolveSize(this.mHeight, heightMeasureSpec);
        this.setMeasuredDimension(this.mWidth, this.mHeight);
        this.maxRadius = this.mWidth / 12;
        this.minRadius = this.maxRadius / 2;

        //Initialize all balls (set colors and brushes, initialize the angle of movement)
        for (int i = 0; i < mBalls.length; i++) {
            this.mBalls[i] = getRandomBall();
        }
    }

    private Ball getRandomBall() {
        Ball mBall = new Ball();
        //Set brush
        setRandomBall(mBall);
        return mBall;
    }

    private void setRandomBall(Ball ball) {
        //Set brush
        final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(randomColor.randomColor());
        paint.setStyle(Paint.Style.FILL);
        paint.setAlpha(180);
        paint.setStrokeWidth(0);
        ball.paint = paint;

        //Set speed
        final float speedX = (this.mRandom.nextInt(this.maxSpeed - this.minSpeed + 1) + 5) / 10f;
        final float speedY = (this.mRandom.nextInt(this.maxSpeed - this.minSpeed + 1) + 5) / 10f;
        ball.vx = this.mRandom.nextBoolean() ? speedX : -speedX;
        ball.vy = -speedY;

        ball.radius = mRandom.nextInt(maxRadius + 1 - minRadius) + minRadius;
        ball.cx = mRandom.nextInt(mWidth - ball.radius) + ball.radius;
        ball.cy = mHeight - ball.radius;
    }

    @Override
    protected void onDraw(final Canvas canvas) {
        final long startTime = System.currentTimeMillis();
        //Draw all the circles first
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            canvas.drawCircle(ball.cx, ball.cy, ball.radius, ball.paint);
        }

        //Ball collision boundary
        for (int i = 0; i < this.mCount; i++) {
            collisionDetectingAndChangeSpeed(mBalls[i]); //  Calculation of collision boundary
            mBalls[i].move(); //  move
        }

        final long stopTime = System.currentTimeMillis();
        final long runTime = stopTime - startTime;
        //Once every 16 milliseconds
        this.postInvalidateDelayed(Math.abs(runTime - 16));
    }

    //Judge whether the ball collides with the collision boundary
    public void collisionDetectingAndChangeSpeed(Ball ball) {
        final int left = 0;
        final int top = 0;
        final int right = this.mWidth;
        final int bottom = this.mHeight;

        final float speedX = ball.vx;
        final float speedY = ball.vy;

        //The velocity of X is reversed around the collision. The judgment of speed is to prevent repeated collision detection, and then stick it to the wall ==
        if (ball.left() <= left && speedX < 0) {
            ball.vx = -ball.vx;
        } else if (ball.top() <= top && speedY < 0) {
            setRandomBall(ball);
        } else if (ball.right() >= right && speedX > 0) {
            ball.vx = -ball.vx;
        }
    }
}

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]