刚开始学习android,接触到了android2D图像的处理,今天弄了好久才将一张图片显示出来,与大家分享分享,在android2.2平台上运行了,没问题,很简单的一个晓得事例,显示一个图片
因为我是新手,这些东西难免可能不是最佳的,写得不是很好,大家别笑话,请各位朋友推荐一些好的方法
下面是主的activity的源码Test_4Activity .java
package chenjiang.android.Test_4;
import android.app.Activity;
import android.os.Bundle;
public class Test_4Activity extends Activity {
GameView gameView=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView=new GameView(this);
setContentView(gameView);
}
}
我看的是android应用开发揭秘这本书,我感觉这本是android的书籍里面写的不错的一本,所以给大家推荐推荐,大家有什么好的关于android的书籍希望能够给我推荐一下,因为参考这本书,所以风格和这本书风格类似。
GameView.java
package chenjiang.android.Test_4;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class GameView extends SurfaceView implements Callback, Runnable {
Bitmap bitmap3=null;
Bitmap bitmap1=null;
Bitmap bitmap2=null;
boolean mbLoop=false;
Paint paint1=null;
Paint paint2=null;
public static float width,height;
//?
SurfaceHolder surfaceHolder=null;
//构造函数
public GameView(Context context) {
super(context);
paint1=new Paint();
paint2=new Paint();
bitmap1=((BitmapDrawable)getResources().getDrawable(R.drawable.tu1)).getBitmap();
bitmap2=((BitmapDrawable)getResources().getDrawable(R.drawable.tu2)).getBitmap();
bitmap3=((BitmapDrawable)getResources().getDrawable(R.drawable.tu3)).getBitmap();
width=bitmap1.getWidth();
height=bitmap1.getHeight();
surfaceHolder=this.getHolder();//获取surffaceHolder对象
surfaceHolder.addCallback( this);
this.setFocusable(true);
//创建时将其设为true
mbLoop = true;
}
// 在surface创建时激发
public void surfaceCreated(SurfaceHolder holder)
{
//开启绘图线程
new Thread(this).start();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
//将surfaceholder锁住,先绘制好了之后再解锁
synchronized(surfaceHolder)
{
draw();
}
}
private void draw() {
Canvas canvas=surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
paint1.setColor(Color.BLACK);
paint2.setColor(Color.WHITE);
canvas.drawLine(45, 5, 445, 5, paint2);
canvas.drawBitmap(bitmap1, 0,0,paint1);
canvas.drawBitmap(bitmap2,width,0,paint2);
canvas.drawBitmap(bitmap3,width*2, 0, paint2);
surfaceHolder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mbLoop=false;
}
}
这里还需要用到图片,我顺便就将其传上来了