import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import java.util.Random;
public class MySurfaceView extends SurfaceView implements Runnable, SurfaceHolder.Callback {
private final String TAG = this.getClass().getName();
private final SurfaceHolder mHolder;
Star[] stars = new Star[200];
Paint paint = new Paint();
Random random = new Random();
public MySurfaceView(Context context) {
this(context, null);
}
public MySurfaceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mHolder = getHolder();
mHolder.addCallback(this);
paint.setAntiAlias(true);
paint.setTextSize(80);
paint.setColor(Color.WHITE);
//初始化 星星
for (int i = 0; i < stars.length; i++) {
stars[i] = new Star();
}
}
private void drawStar(Canvas canvas) {
for (Star s : stars) {
if (s.x == 0) {
s.x = random.nextInt(getWidth());
s.y = random.nextInt(getHeight());
}
s.smoothTwinkle();
canvas.drawCircle(s.x, s.y, s.r, paint);
}
}
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
Log.i(TAG, "surfaceCreated=");
setWillNotDraw(false);
new Thread(this).start();
}
@Override
public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged=");
}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
Log.i(TAG, "surfaceDestroyed=");
}
//第一种方法 使用surfaceview 绘制
@Override
public void run() {
try {//try catch 用途:home键 或 息屏 时 ,mHolder 和 canvas 会报错
Canvas canvas = mHolder.lockCanvas();
//SurfaceView 清屏
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
drawStar(canvas);
mHolder.unlockCanvasAndPost(canvas);
postDelayed(this, 50);
}catch (Exception e){
Log.e(TAG,"run-ex="+e.getMessage());
}
}
//第二种方法 使用 view 本身绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// drawStar(canvas);
//postInvalidateDelayed(50);
}
class Star {
int x, y;
float r = new Random().nextInt(5) + 1;
float fixR = 0.5f;
float maxR = 5;
float minR = 1;
boolean isRadd = false;
//闪烁
public void twinkle(){
r=random.nextInt(5)+1;
}
//平滑闪烁
public void smoothTwinkle(){
if (isRadd) {
r += fixR;
if (r > maxR) {
r = maxR;
isRadd = false;
}
} else {
r -= fixR;
if (r < minR) {
r = minR;
isRadd = true;
}
}
}
}
}
demo 下载地址:https://download.csdn.net/download/qq_29364417/80805271
|