package com.example.surfaceviewsample;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 이걸 써주면 타이틀바가 잠시 나왔다가 사라진다.
requestWindowFeature(Window.FEATURE_NO_TITLE);
CustomView view = new CustomView(this);
view.getHolder().setFormat(PixelFormat.TRANSLUCENT); //서피스뷰 투명 배경
setContentView(view);
//setContentView(R.layout.activity_main);
}
@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;
}
class CustomView extends SurfaceView implements SurfaceHolder.Callback {
private CustomViewThread cvt;
Bitmap bm;
public CustomView(Context context) {
super(context);
getHolder().addCallback(this);
cvt = new CustomViewThread(getHolder(), this);
bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
@Override
public void onDraw(Canvas canvas) {
//canvas.drawBitmap(bm, 64, 64, null);
// 여기서는 안그려짐.
// Paint paint = new Paint();
// paint.setColor(Color.WHITE);
// canvas.drawCircle(100, 100, 50, paint);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
cvt.setRunning(true);
cvt.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
cvt.setRunning(false);
while (retry) {
try {
cvt.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
class CustomViewThread extends Thread {
private SurfaceHolder surfaceholder;
private CustomView customview;
private boolean running = false;
public CustomViewThread(SurfaceHolder surfaceHolder, CustomView CustomView) {
surfaceholder = surfaceHolder;
customview = CustomView;
}
public void setRunning(boolean run) {
running = run;
}
@Override
public void run() {
Canvas c;
while (running) {
c = null;
try {
c = surfaceholder.lockCanvas(null);
synchronized (surfaceholder) {
// onDraw는 android-18에서는 호출이 안되게 막혀있다.
// customview.onDraw(c);
// draw는 call해서 onDraw가 불리게 할수는 있지만 onDraw에서 그리면 안그려진다.
// customview.draw(c);
// 여기서 직접 그려야 한다.
Paint paint = new Paint();
paint.setColor(Color.WHITE);
c.drawCircle(100, 100, 50, paint);
// 아이콘 그리기.
c.drawBitmap(customview.bm, 64, 64, null);
}
} finally {
if (c != null) {
surfaceholder.unlockCanvasAndPost(c);
}
}
}
}
}
}
No comments:
Post a Comment