您的位置:首页 > 移动开发 > Android开发

android一连串图片组成动画

2016-03-21 23:26 417 查看
/**
* 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;
}

}

}
};
}

图片位置



演示图片:

百度云盘下载

演示截图


  


   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: