package ccc.canvasDemo;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class canvasDemo extends Activity {
SurfaceView SurfaceView01;
SurfaceHolder surfaceHolder;
Drawable drawable;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drawable = getResources().getDrawable(R.drawable.android);
Button button01 = (Button) findViewById(R.id.Button01);
button01.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
draw(drawAction.drawAndroid);
}
});
Button button02 = (Button) findViewById(R.id.Button02);
button02.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
draw(drawAction.clear);
}
});
Button button03 = (Button) findViewById(R.id.Button03);
button03.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
SurfaceView01 = (SurfaceView) findViewById(R.id.SurfaceView01);
surfaceHolder = SurfaceView01.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder arg0) {
}
public void surfaceCreated(SurfaceHolder arg0) {
draw(drawAction.create);
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
int arg3) {
}
});
}
@Override
protected void onResume() {
super.onResume();
}
enum drawAction {
create, drawAndroid, clear,
}
void draw(drawAction action) {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
switch (action) {
case create:
start(canvas);
break;
case drawAndroid:
drawAndroid(canvas);
break;
case clear:
clear(canvas);
break;
}
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
void drawAndroid(Canvas canvas) {
Paint p = new Paint();
p.setARGB(150, 88, 88, 88);
canvas.drawLine(0, 0, 128, 128, p);
canvas.save();
drawable.setBounds(64, 64, 128, 128);
float angle = 90;
canvas.rotate(angle, drawable.getBounds().centerX(), drawable
.getBounds().centerY());
drawable.draw(canvas);
canvas.restore();
}
void start(Canvas canvas) {
drawable.setBounds(0, 0, 128, 128);
drawable.draw(canvas);
}
void clear(Canvas canvas) {
Paint p = new Paint();
p.setARGB(255, 0, 0, 0);
Rect rect = new Rect(0, 0, SurfaceView01.getWidth(), SurfaceView01
.getHeight());
canvas.drawRect(rect, p);
}
}
沒有留言:
張貼留言