【Android實戰】SurfaceView繪制各種效果Demo


1、狂奔的炸彈

public class MySurface extends SurfaceView implements Callback, Runnable {
SurfaceHolder holder;
boolean goOn = true;
int w;
int h;
Bitmap bitmap;
int x;
int y;
int bx;
int by;
boolean down = true;
boolean right = true;
int p = 30;

public MySurface(Context context, int wi, int hi) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
holder.addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
w = wi;
h = hi;
Bitmap obitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.b1);
bitmap = Bitmap.createScaledBitmap(obitmap, 260, 200, false);
bx = bitmap.getWidth();
by = bitmap.getHeight();
Thread t = new Thread(this);

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Thread t = new Thread(this);
t.start();
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
goOn = false;
}

@Override
public void run() {
// TODO Auto-generated method stub
while (goOn) {
myDraw();
try {
if (y < h - by && down) {
y += p;

} else {
down = false;
if (x < w - bx && right) {
x += p;
} else {
right = false;
if (y > 0 && !down) {
y -= p;
} else {

if (x > 0 && !right) {
x -= p;
} else {
down = true;
right = true;
}
}
}
}

Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Canvas canvas;

private void myDraw() {
// TODO Auto-generated method stub
canvas = holder.lockCanvas();
if (canvas != null) {
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
canvas.drawColor(Color.GRAY);
try {
if (canvas != null) {
canvas.drawBitmap(bitmap, x, y, null);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}

2、用view繪制一個扇形

public class MySxView extends View {

String title[] = { "四川", "重慶", "北京", "上海", "南京", "深圳" };

public MySxView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(400, 400, 300, paint);
int each = 360 / title.length;
Paint p1 = new Paint();
Paint p2 = new Paint();
Paint p3 = new Paint();
p1.setColor(Color.BLUE);
p2.setColor(Color.YELLOW);
p3.setColor(Color.WHITE);
for (int i = 0; i < title.length; i++) {
RectF oval = new RectF(100,100,700,700);
canvas.drawArc(oval, i * each, each, true, i % 2 == 0 ? p1 : p2);

}

}
}




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com