您的位置:首页技术文章
文章详情页

Android自定义UI之粒子效果

【字号: 日期:2022-09-22 08:59:28浏览:8作者:猪猪

本文实例为大家分享了Android自定义UI之粒子效果的具体代码,供大家参考,具体内容如下

1.爆炸实体类

public class Ball { public int color;//颜色 public float x;//圆心x坐标 public float y;//圆心y坐标 public float r;//粒子半径 public float vX;//粒子水平方向速度 public float vY;//粒子y方向速度 public float aX;//粒子水平方向加速度 public float ay;//粒子y方向加速度}

2.自定义SplitView类

import android.animation.ValueAnimator;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Paint;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.view.animation.LinearInterpolator;import androidx.annotation.Nullable;import java.util.ArrayList;import java.util.List;public class SplitView extends View { private Paint mPaint; private Bitmap mBitmap; private float d=3;//粒子直径 private ValueAnimator mAnimator; private List<Ball> mBalls=new ArrayList<>(); public SplitView(Context context) { super(context); } public SplitView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public SplitView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint=new Paint(); mBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background); for (int i=0;i<mBitmap.getWidth();i++){ for (int j =0;j<mBitmap.getHeight();j++){Ball ball=new Ball();ball.color=mBitmap.getPixel(i,j);ball.x=i*d+d/2;ball.y=j*d+d/2;ball.r=d/2;//速度(-20,20)ball.vX=(float)(Math.pow(-1,Math.ceil(Math.random()*1000))*20*Math.random());ball.vY=rangInt(-15,35);ball.aX=0;ball.ay=0.98f;mBalls.add(ball); } } mAnimator=ValueAnimator.ofFloat(0,1); mAnimator.setRepeatCount(-1);//重复次数无限 mAnimator.setDuration(2000);//重复时间 mAnimator.setInterpolator(new LinearInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) {upDateBall();invalidate();//重新调用onMeasure,ondraw方法。 } }); } private int rangInt(int x,int y){ int max=Math.max(x,y); int min=Math.min(x,y); return (int)(min+Math.ceil(Math.random()*(max-min))); } private void upDateBall() { for (Ball ball:mBalls){ ball.x=ball.x+ball.vX; ball.y=ball.y+ball.vY; ball.vX+=ball.aX; ball.vY+=ball.ay; } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.translate(500,500); for (Ball ball:mBalls){ mPaint.setColor(ball.color); canvas.drawCircle(ball.x,ball.y,ball.r,mPaint); } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction()==MotionEvent.ACTION_DOWN) { //触发动画 mAnimator.start(); } return super.onTouchEvent(event); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Android
相关文章: