3

我在 Android 上预览相机时遇到了一些问题。

现在我有一个按钮,你需要先按下才能预览相机。但是我想在您启动应用程序后立即进行预览。

如果我尝试从按钮中取出开始预览的部分并将其放入 onCreate,它将不起作用,预览将不会开始。

如何在用户无需触摸按钮的情况下创建预览?

另外,我有一台 HTC Desire HD,预览对我来说是 90 度。为什么会这样?

Camera cam;
SurfaceView surf;
SurfaceHolder holder;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btnStart= (Button)findViewById(R.id.startCamPrev);

    getWindow().setFormat(PixelFormat.UNKNOWN);

    surf = (SurfaceView)findViewById(R.id.surfaceView);

    holder = surf.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    btnStart.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View arg0) {
            cam = Camera.open();
            if(cam != null)
            {
                try
                {
                    cam.setPreviewDisplay(holder);
                    cam.startPreview();
                }
                catch(IOException e)
                {
                }
            }
        }
    });
}

清单文件:

     <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="LSAB.CamTest"
         android:versionCode="1"
         android:versionName="1.0">
       <application android:icon="@drawable/icon" android:label="@string/app_name">
           <activity android:name=".CameraTest"
                     android:label="@string/app_name">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>

       </application>
       <uses-sdk android:minSdkVersion="4" />

    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    </manifest>

主要.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Hello World, CameraTest"
    />
<Button
    android:id = "@+id/startCamPrev"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="- Start Preview -"
    />
 <SurfaceView
     android:id="@+id/surfaceView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     />
</LinearLayout>
4

2 回答 2

2

除了添加setPreviewDisplayonCreate尝试做->

实施SurfaceHolder.Callback

onSurfaceChanged方法中,setPreviewDisplay使用传递给该方法的新 surfaceHolder 进行重置。

这对我有用..

于 2011-06-14T12:04:55.457 回答
0

您是否检查过清单中的权限?也尽量不要在 OnCreate 中做那么多,这是一种不好的做法,请看在上帝的份上,如果您需要帮助,请评论代码。

好的,尝试更改布局的方向并告诉我会发生什么。

于 2011-06-04T21:28:27.197 回答