Android中实现调用摄像头拍照并显示在ImageView中
生活随笔
收集整理的這篇文章主要介紹了
Android中实现调用摄像头拍照并显示在ImageView中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
點擊拍照按鈕調用系統攝像機進行拍照,并將拍的照片顯示在ImageView中。
?
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
新建一個Activity,設計其布局如下
?
布局xml文件為
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".CameraActivity"><Buttonandroid:id="@+id/button"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="啟動攝像頭" /><ImageViewandroid:id="@+id/iv_camera"android:layout_width="350dp"android:layout_height="350dp"android:layout_gravity="center"android:layout_marginTop="20dp" /></LinearLayout>然后在對應的Activity中,通過指定Action的Intent來調用系統攝像頭,并采用帶返回結果的方式啟動Activity,
然后在重寫的獲取Activity返回結果的方法中,判斷請求碼與上面自定義的常量一致并且請求結果為OK
那么通過將data強轉為Bitmap并給ImageView設置數據源進行顯示
package com.badao.androidstudy;import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity;import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView;public class CameraActivity extends AppCompatActivity {private Button btnCamera;private ImageView imageView;private final int CAMERA_REQUEST = 10;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_camera);initView();}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);switch (requestCode) {case CAMERA_REQUEST:if (resultCode == RESULT_OK) {Bitmap bitmap = (Bitmap) data.getExtras().get("data");imageView.setImageBitmap(bitmap);}break;}}public void initView(){imageView = findViewById(R.id.iv_camera);btnCamera = findViewById(R.id.button);btnCamera.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(intent,CAMERA_REQUEST);}});} }示例效果
?
?
總結
以上是生活随笔為你收集整理的Android中实现调用摄像头拍照并显示在ImageView中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AndroidStudio中安装Gson
- 下一篇: Android中通过SeekBar手动控