Augmented Reality – II

In my last post I showed how to get position and orientation updates. In this short post (also because it’s quite simple) I’ll show how to integrate it with the camera preview.

To show the camera preview in Android it’s quite easy, just create a class that extends from SurfaceView and implements the SurfaceHolder.Callback methods:

package com.fuzzion.argine.viewer;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraView extends SurfaceView implements SurfaceHolder.Callback, PreviewCallback {
	private Camera camera;
	private boolean running = false;

	public CameraView(Context context) {
		super(context);

		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		setFocusable(true);
		requestFocus();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if(running) {
			camera.stopPreview();
		}

		try {
			camera.setPreviewDisplay(holder);
		} catch(Exception e) {}

		camera.startPreview();
		running = true;
		camera.setPreviewCallback(this);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		try {
			if(camera != null) {
				camera.stopPreview();
				running = false;
				camera.release();
				camera = null;
			}
		} catch(Exception e) {}
	}

	@Override
	public void onPreviewFrame(byte[] data, Camera camera) {

	}
}

It’s really simple, just using the startPreview() / stopPreview methods. To overlay our previous view with the camera preview we have to do that in our Activity main class:

cv = new CameraView(this);
tv = new TestView(this);

setContentView(cv);
addContentView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

We’re adding the camera preview and our previous viewer (removing the background, and changing the arrow color to white) so we can see both views at the same time.

I’ve also implemented the PreviewCallback class to receive callbacks with the camera raw data (byte[]). It might be useful some day..