這邊除了 Camera 預覽外,再使用自訂的 View 加上拍照功能常有的對焦框,為了讓對焦框可以疊在 Camera 預覽視窗上方,就是一定要用 FrameLayout。
CameraOverlayActivity
public class CameraOverlayActivity extends Activity { private static final String TAG = "CameraOverlayActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 全螢幕顯示 this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 不顯示標題列 this.requestWindowFeature(Window.FEATURE_NO_TITLE); // 以程式建立 UI,為了層層相疊,最底層用的是 FrameLayout FrameLayout frmLayout = new FrameLayout(this); // 往上一層是攝影機預覽畫面 SurfaceView sv = new SurfaceView(this); SurfaceHolder sh = sv.getHolder(); // 加入攝影機功能 sh.addCallback(new CameraCallback()); sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); frmLayout.addView(sv); // 最上層是方框 SquareView sqv = new SquareView(this); frmLayout.addView(sqv); setContentView(frmLayout); } }CameraCallback
public class CameraCallback implements SurfaceHolder.Callback { private static final String TAG = "CameraCallback"; private Camera c; @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "啟動相機"); this.c = Camera.open(); try { Log.d(TAG, "設定預覽視窗"); this.c.setPreviewDisplay(holder); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "開始預覽"); this.c.startPreview(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "停止預覽"); this.c.stopPreview(); Log.d(TAG, "釋放相機資源"); this.c.release(); this.c = null; } }SquareView
public class SquareView extends View { private static final String TAG = "SquareView"; public SquareView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.d(TAG, "畫框"); // 黃色的線 Paint p = new Paint(); p.setColor(Color.YELLOW); // 方框 float w = canvas.getWidth(); float h = canvas.getHeight(); // 上下左右四邊 int margin = 90; canvas.drawLine(margin, margin, w - margin, margin, p); canvas.drawLine(margin, h - margin, w - margin, h - margin, p); canvas.drawLine(margin, margin, margin, h - margin, p); canvas.drawLine(w - margin, margin, w - margin, h - margin, p); } }最後在 AndroidManifest.xml 裡加上 android.permission.CAMERA 權限,以及限制 Activity 為橫向即可。
<activity ... android:screenOrientation="landscape">
相關文章
沒有留言:
張貼留言