安卓拍照器应用的开发分为三个主要步骤
1. 调用相机应用
2. 捕获照片
3. 显示照片
1. 调用相机应用
要调用相机应用,需要使用Intent。这个Intent会带给系统启动相机应用,并在相机应用中拍照。
```
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION,IMAGE,CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST,IMAGE,CAPTURE);
}
```
`MediaStore.ACTION,IMAGE,CAPTURE` 操作会启动系统的相机应用,该应用将照相机的预览显示在屏幕上。如果没有照相机应用能够处理这个Intent,`resolveActivity()` 将返回 null。所以呢,在调用 `startActivityForResult()` 之前,要确保有相机应用可以处理该Intent。
2. 捕获照片
拍摄照片后,系统会将原始照片数据保存到文件中,然后返回文件URI,可以使用该URI在应用程序中读取文件并显示照片。默认情况下,照片文件保存在应用程序的私有文件夹中。要获取文件,请在 `onActivityResult()` 方法中处理 `REQUEST,IMAGE,CAPTURE` Intent 的结果,如下所示
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST,IMAGE,CAPTURE && resultCode == RESULT,OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get(data);
mImageView.setImageBitmap(imageBitmap);
}
}
```
在这个方法中,我们从Intent获取了一个 `Bitmap` 对象,该对象包含拍摄的图像文件的缩略图。
3. 显示照片
最后,我们需要在应用程序中显示照片。可以使用ImageView来显示图像,如下所示
```
安卓:id=@+id/imageView
安卓:layout,width=match,parent
安卓:layout,height=match,parent
安卓:scaleType=centerCrop />
```
在上面的布局中,我们使用 `安卓:scaleType=centerCrop` 属性来使图像缩放到View的大小,并保持其宽高比,同时尽量充满整个View。
最后,从文件读取图像并在ImageView中显示它。
参考代码如下
```
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
```
在这个方法中,我们首先获取ImageView的大小。然后,从文件中读取图像文件并计算出应该缩放的比例。最后使用 BitmapFactory.decodeFile() 方法,将图像文件解码为Bitmap,并使用 `mImageView.setImageBitmap()` 方法把它设置为ImageView的内容。