我在這個主題上看到了一些主題,但他們似乎都沒有回答這個問題,所以,我再給它一個...如何將圖形放在Android相機預覽的頂部?
非常簡單的想法...我想要一些部分屏幕預覽(和拍攝)相機和屏幕的其他部分以添加我自己的圖形元素(按鈕,圍繞相機預覽的多彩框架等)。
Android自帶的例子填滿了屏幕。顯而易見的解決方案(似乎沒有工作)是使用我自己的SurfaceView(而不是他們在示例中所做的),並將它放在我的XML中。代碼(在下面)不會崩潰,並報告它正在啓動相機......它只是不會在屏幕上呈現。
我不知道我做錯了什麼。我的猜測是,它與顯示線程有關,從不會在渲染初始屏幕後重繪任何東西,但我甚至嘗試添加一個按鈕並啓動相機以在按鈕單擊時在表面視圖上呈現,但是並沒有進一步激怒它。我認爲這是正確的,我認爲在事實之後,我如何將視圖拉進去,這是錯誤的。
任何和所有幫助非常感謝。
public class TakePhoto extends Activity implements SurfaceHolder.Callback{
/** Called when the activity is first created. */
SurfaceHolder mHolder;
Camera mCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.take_photo);
try{
SurfaceView sv = (SurfaceView) findViewById(R.id.camera_surface);
mHolder = sv.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
toast("added callback");
}catch(Exception e){
toast("push: " + e);
}
}
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
toast("error:" + exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w/h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Size size : sizes) {
double ratio = (double) size.width/size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
private void toast(String str){
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, str, duration);
toast.show();
}
}