Android 气泡动画(自定义View类)

Android 气泡动画(自定义View类)

一、前言

最近有需求制作一个水壶的气泡动画,首先在网上查找了一番,找到了一个文章。

https://blog.csdn.net/u010386612/article/details/50580080

测试了一下发现,如果把它作为子视图的话,会出现小球溢出边界的情况。所以简单的修改了一下。

二、代码

1. 随机移动的气泡

Ball类

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

    // 圆心
    @kotlin.jvm.JvmField
    var cx = 0f

    // 圆心
    @kotlin.jvm.JvmField
    var cy = 0f

    // X轴速度
    @kotlin.jvm.JvmField
    var vx = 0f

    // Y轴速度
    @kotlin.jvm.JvmField
    var vy = 0f

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

    // 移动
    fun move() {
        //向角度的方向移动,偏移圆心
        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类

/**
 * @author jiang yuhang
 * @date 2021-04-18 19:53
 */
public class BallView extends View {
    private final Random mRandom;
    private final int mCount = 5;   // 小球个数
    private final int minSpeed = 5; // 小球最小移动速度
    private final int maxSpeed = 20; // 小球最大移动速度

    public Ball[] mBalls;   // 用来保存所有小球的数组
    private int maxRadius;  // 小球最大半径
    private int minRadius; // 小球最小半径
    private int mWidth = 200;
    private int mHeight = 200;

    public BallView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        // 初始化所有球(设置颜色和画笔, 初始化移动的角度)
        this.mRandom = new Random();
        final RandomColor randomColor = new RandomColor(); // 随机生成好看的颜色,github开源库。
        this.mBalls = new Ball[this.mCount];

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

            // 设置速度
            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;

        // 初始化圆的半径和圆心
        for (Ball mBall : this.mBalls) {
            mBall.radius = this.mRandom.nextInt(this.maxRadius + 1 - this.minRadius) + this.minRadius;
            // 初始化圆心的位置, x最小为 radius, 最大为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();
        // 先画出所有圆
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            canvas.drawCircle(ball.cx, ball.cy, ball.radius, ball.paint);
        }

        // 球碰撞边界
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            this.collisionDetectingAndChangeSpeed(ball); // 碰撞边界的计算
            ball.move(); // 移动
        }

        final long stopTime = System.currentTimeMillis();
        final long runTime = stopTime - startTime;
        // 16毫秒执行一次
        this.postInvalidateDelayed(Math.abs(runTime - 16));
    }

    // 判断球是否碰撞碰撞边界
    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;

        // 碰撞左右,X的速度取反。 speed的判断是防止重复检测碰撞,然后黏在墙上了=。=
        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.热水气泡

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

    // 圆心
    @kotlin.jvm.JvmField
    var cx = 0f

    // 圆心
    @kotlin.jvm.JvmField
    var cy = 0f

    // X轴速度
    @kotlin.jvm.JvmField
    var vx = 0f

    // Y轴速度
    @kotlin.jvm.JvmField
    var vy = 0f

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

    // 移动
    fun move() {
        //向角度的方向移动,偏移圆心
        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(); // 随机生成好看的颜色,github开源库。
    private final Random mRandom = new Random();
    private final int mCount = 5;   // 小球个数
    private final int minSpeed = 5; // 小球最小移动速度
    private final int maxSpeed = 15; // 小球最大移动速度
    public Ball[] mBalls = new Ball[this.mCount];   // 用来保存所有小球的数组
    private int maxRadius;  // 小球最大半径
    private int minRadius; // 小球最小半径
    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;

        // 初始化所有球(设置颜色和画笔, 初始化移动的角度)
        for (int i = 0; i < mBalls.length; i++) {
            this.mBalls[i] = getRandomBall();
        }
    }

    private Ball getRandomBall() {
        Ball mBall = new Ball();
        // 设置画笔
        setRandomBall(mBall);
        return mBall;
    }

    private void setRandomBall(Ball ball) {
        // 设置画笔
        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;

        // 设置速度
        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();
        // 先画出所有圆
        for (int i = 0; i < this.mCount; i++) {
            final Ball ball = this.mBalls[i];
            canvas.drawCircle(ball.cx, ball.cy, ball.radius, ball.paint);
        }

        // 球碰撞边界
        for (int i = 0; i < this.mCount; i++) {
            collisionDetectingAndChangeSpeed(mBalls[i]); // 碰撞边界的计算
            mBalls[i].move(); // 移动
        }

        final long stopTime = System.currentTimeMillis();
        final long runTime = stopTime - startTime;
        // 16毫秒执行一次
        this.postInvalidateDelayed(Math.abs(runTime - 16));
    }

    // 判断球是否碰撞碰撞边界
    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;

        // 碰撞左右,X的速度取反。 speed的判断是防止重复检测碰撞,然后黏在墙上了=。=
        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;
        }
    }
}

在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现一个气泡动画,并且不可以超出屏幕,可以使用 ValueAnimator View 的 layout 参数。以下是一个简单的示例代码,可以让一个气泡在屏幕中进行弹跳动画: MainActivity.java: ``` public class MainActivity extends AppCompatActivity { private ImageView bubble; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bubble = findViewById(R.id.bubble); ValueAnimator animator = ValueAnimator.ofFloat(0, 1); animator.setDuration(2000); animator.setInterpolator(new LinearInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); float x = calculateX(value); float y = calculateY(value); bubble.setX(x); bubble.setY(y); } }); animator.start(); } private float calculateX(float value) { // 计算 x 坐标 float x = value * 500; // 500 是屏幕的宽度 if (x < bubble.getWidth() / 2) { return bubble.getWidth() / 2; } if (x > 500 - bubble.getWidth() / 2) { return 500 - bubble.getWidth() / 2; } return x; } private float calculateY(float value) { // 计算 y 坐标 float y = (float) (400 * Math.sin(value * Math.PI)); if (y < bubble.getHeight() / 2) { return bubble.getHeight() / 2; } if (y > 800 - bubble.getHeight() / 2) { return 800 - bubble.getHeight() / 2; } return y; } } ``` 在这个示例中,我们创建了一个 ValueAnimator 对象,设置了动画时间为 2 秒,插值器为 LinearInterpolator(线性插值器),然后添加了一个动画更新监听器,在监听器中计算出当前时间点的 x 和 y 坐标,并将其应用到 ImageView 上。在 calculateX() 方法中,我们简单地将 x 坐标设置为时间的线性函数,这将导致气泡水平移动。但是,我们还需要确保气泡不会超出屏幕范围,因此我们使用了一些条件语句来限制气泡的位置。在 calculateY() 方法中,我们使用正弦函数来计算出 y 坐标,这将导致气泡上下移动,并产生弹跳的效果。同样,我们使用条件语句来确保气泡不会超出屏幕范围。最后,我们使用 start() 方法启动动画
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值