Balloon collision effect of android custom View

Keywords: SurfaceView

Recently, a lot of small ball collision effects need to be done in the project, so a user-defined View is used to roll it out. The effects are as follows

This effect is not complicated. Let's talk about the algorithm steps.
1. ballCount is the number of small balls. You can set a maximum value to remove random numbers within this threshold
2. The random coordinates (mX, mY) and radius of the center of the sphere
3. The random velocities of the ball in x and y directions mSpeedX, mSpeedY
4. This effect is white by default. You can set transparency through alpha. In fact, you can also use random color values to achieve the effect of colorful frequent balls.
5. Each ball is initially given an initial random position (no more than the screen) and an initial random speed.
6. Calculate the position of the ball and refresh the interface for each period of time. When the ball reaches the edge of the screen, the speed is set to the current opposite number to achieve the rebound effect.
In order to achieve a good refresh effect, this user-defined SurfaceView is implemented. The main code is as follows:

private void initBalls() {
    ballBeans = new BallBean[mBallCount];
    for (int i = 0; i < ballBeans.length; i++) {
        ballBeans[i] = new BallBean();
        ballBeans[i].setRadius((new Random().nextInt(mMaxSize-mMinSize) + mMinSize)/2);
        ballBeans[i].setX(new Random().nextInt(mViewWidth-ballBeans[i].getRadius()));
        ballBeans[i].setY(new Random().nextInt(mViewHeight-ballBeans[i].getRadius()));
        ballBeans[i].setSpeedY(new Random().nextBoolean()?(new Random().nextInt(4) + mSpeedY):-(new Random().nextInt(4) + mSpeedY));
        ballBeans[i].setSpeedX(new Random().nextBoolean()?(new Random().nextInt(4) + mSpeedX):-(new Random().nextInt(4) + mSpeedX));
        ballBeans[i].setAlpha(new Random().nextInt(255));

//Update position and speed direction
private void updatePara() {
    int x;
    int y;
    for (BallBean ball : ballBeans) {
        if (ball == null) {
        x = ball.getX() + ball.getSpeedX();
        y = ball.getY() + ball.getSpeedY();
        if((x-ball.getRadius())<=0 || (x+ball.getRadius())>=mViewWidth){
        }else {
        if((y-ball.getRadius())<=0 || (y-ball.getRadius())>=mViewHeight){
        }else {


private void drawView() {
    if (surfaceHolder == null) {
    Canvas canvas = surfaceHolder.lockCanvas();
    if (canvas == null) {
    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

private void drawBall(Canvas canvas) {
    for (BallBean ballbean : ballBeans) {
Engineering source code

Posted by ratass2002 on Sat, 15 Feb 2020 09:21:13 -0800