程序运行截图
程序实现的效果是
不断的改变圆形的颜色
代码
MainAcitivity.java
package com.example.surfaceviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
private GameSurfaceView gameSurfaceView=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
gameSurfaceView=new GameSurfaceView(this);
super.onCreate(savedInstanceState);
setContentView(gameSurfaceView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
GameSurfaceView.java
package com.example.surfaceviewdemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable
{
boolean mbLoop=false;
SurfaceHolder mSurfaceHolder=null;
int miCount=0;
int y=50;
public GameSurfaceView(Context context)
{
super(context);
mSurfaceHolder=this.getHolder();
mSurfaceHolder.addCallback(this);
this.setFocusable(true);
mbLoop=true;
}
public void surfaceCreated(SurfaceHolder holder)
{
new Thread(this).start();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
mbLoop=false;
}
public void run()
{
while(mbLoop)
{
try
{
Thread.sleep(200);
}
catch(Exception e)
{
}
synchronized(mSurfaceHolder)
{
Draw();
}
}
}
public void Draw()
{
Canvas canvas=mSurfaceHolder.lockCanvas();
if(mSurfaceHolder==null||canvas==null)
{
return;
}
if(miCount<100)
{
miCount++;
}
else
{
miCount=0;
}
Paint mPaint=new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLACK);
canvas.drawRect(0,0,320,480,mPaint);
switch(miCount%4)
{
case 0:
mPaint.setColor(Color.BLUE);
break;
case 1:
mPaint.setColor(Color.GREEN);
break;
case 2:
mPaint.setColor(Color.RED);
break;
case 3:
mPaint.setColor(Color.YELLOW);
break;
default:
mPaint.setColor(Color.WHITE);
break;
}
canvas.drawCircle((320-25)/2,y,50,mPaint);
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
注
代码摘自
<<android 应用开发揭秘>>
一书