/**
* Created by Bellion on 2016/3/21.
*/
public class PersonRunSurface extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PersonGoSurface";
private Context mContext;
private SurfaceHolder mHolder;
private int widthPixels;
private String[] runs;
public PersonRunSurface(Context context) {
super(context);
init(context);
}
public PersonRunSurface(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PersonRunSurface(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.mContext = context;
//1 获取Holder
mHolder = getHolder();
//2.添加回调
mHolder.addCallback(this);
//3获取屏幕宽高 以及资源文件
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
Log.i(TAG, "widthPixels:" + widthPixels + "heightPixels:" + heightPixels);
try {
runs = context.getAssets().list("run");
} catch (IOException e) {
e.printStackTrace();
}
}
//重写的SurfaceHolder.Callback的方法
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
Thread thread = new Thread(){
@Override
public void run() {
super.run();
Paint paint = new Paint();
paint.setAntiAlias(true);
boolean isRun = true;
boolean direction = true;
int position = 0;
float locationX = 0;
float step = 13;
while(isRun){
Canvas canvas = mHolder.lockCanvas();
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawPaint(clearPaint);
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
int imgWidth = 0;
try {
InputStream open = mContext.getAssets().open("run" + "/" + runs[position]);
Bitmap bitmap = BitmapFactory.decodeStream(open);
imgWidth = bitmap.getWidth();
canvas.drawBitmap(bitmap,locationX,200,paint);
} catch (IOException e) {
e.printStackTrace();
}
mHolder.unlockCanvasAndPost(canvas);
position ++;
//判断方向
if (direction) {
locationX += step;
} else {
locationX -= step;
}
//由当前位置判断应该行走的方向
if (locationX >= widthPixels - imgWidth/2) {
direction = false;
}else if (locationX <= (-imgWidth/2)) {
direction = true;
}
try {
sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
//加载某张图片
if (position >= runs.length) {
position = 0;
}
}
}
};
}
图片位置
演示图片:
演示截图