新年到了拙徽,本文將展示通過自定義view繪制煙花效果的案例煤墙,同時(shí)介紹一種優(yōu)化canvas繪制時(shí)的性能的方法.
效果展示
每點(diǎn)擊一下屏幕會產(chǎn)生一枚煙花晌块,煙花飛到最上空會炸裂成60~100個(gè)碎片瘤载,
同屏可能有上千個(gè)粒子在不停更新它的位置.
項(xiàng)目地址
代碼分析
- 首先項(xiàng)目結(jié)構(gòu)
└─fireworks
ColorfullView.java -自定義的view
Firework.java -對煙花建立模型
MainActivity.java
Particle.java -粒子
PContext.java -工具類
PVector.java -向量類
- 使用GestureDetector處理用戶輸入,每點(diǎn)擊一次在當(dāng)前位置創(chuàng)建一枚煙花
mGesture = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
fireworks.add(new Firework(e.getX(), e.getY()));
ViewCompat.postInvalidateOnAnimation(ColorfullView.this);
return true;
}
});
- FireWork類包含兩個(gè)屬性
ArrayList<Particle> particles; // 炸開后的粒子
Particle firework; // 炸開前的粒子
- Particle類具有隨機(jī)的顏色癣疟、大小挣柬、速度以接近真實(shí)
- 每繪制一幀會調(diào)用FireWork的run方法,該方法中會調(diào)用當(dāng)前粒子的update和display方法
void run(Canvas canvas, Paint paint) {
if (firework != null) {//炸裂前
firework.applyForce(gravity);
firework.update();
firework.display(canvas, paint);
if (firework.explode()) {
int fragments = (int) random(60, 100);//碎片個(gè)數(shù)
for (int i = 0; i < fragments; i++) {
particles.add(new Particle(firework.location, hu)); // Add "num" amount of particles to the arraylist
}
firework = null;
firstExplode = true;
}
} else {//炸裂后
if (firstExplode) {//屏幕一閃
firstExplode = false;
canvas.drawColor(Color.HSVToColor(new float[]{hu, 0.6f, 0.6f}));
}
for (int i = particles.size() - 1; i >= 0; i--) {
Particle p = particles.get(i);
p.applyForce(gravity);
p.update();
p.display(canvas, paint);
if (p.isDead()) {
particles.remove(i);
}
}
}
}
性能優(yōu)化
這時(shí)候功能基本實(shí)現(xiàn)了睛挚,剩下的就是將每一個(gè)煙花繪制在canvas上邪蛔,通常我們會這樣寫
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
for (int i = fireworks.size() - 1; i >= 0; i--) {
Firework f = fireworks.get(i);
f.run(canvas, mParticlePaint);
if (f.done()) {
fireworks.remove(i);
}
}
//canvas.drawBitmap(canvasBitmap,0, 0, mBitmapPaint);
if (!fireworks.isEmpty()) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
然而你會發(fā)現(xiàn)性能很糟糕,幀數(shù)隨著粒子數(shù)的增加直線下降直到個(gè)位數(shù),優(yōu)化如下
@Override
protected void onDraw(Canvas canvas) {
if (canvasBitmap == null || canvasBitmap.isRecycled()) {
canvasBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(canvasBitmap);
mBitmapShader = new BitmapShader(canvasBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setShader(mBitmapShader);
mBitmapPaint.setDither(false);
}
bitmapCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
for (int i = fireworks.size() - 1; i >= 0; i--) {
Firework f = fireworks.get(i);
f.run(bitmapCanvas, mParticlePaint);
if (f.done()) {
fireworks.remove(i);
}
}
canvas.drawPaint(mBitmapPaint);
if (!fireworks.isEmpty()) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
Thanks
some codes were from Daniel Shiffman