Android手機拍照功能實現

1.Photo.xml文件設置佈局空間:ImageView 和 Button  實現點擊按鈕顯示照片

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <ImageView
            android:id="@+id/photoiv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/photobtn"
            android:textColor="拍照"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

2.java文件配置代碼

package com.example.bf.photo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ImageView photoiv;
    Button photobtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        photoiv=findViewById(R.id.photoiv);
        photobtn=findViewById(R.id.photobtn);

        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if (requestCode == 1) {
                    if (resultCode == Activity.RESULT_OK) {
                        Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                        photoiv.setImageBitmap(bitmap);
                    }
            }
        }

        photobtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,1);
            }
        });

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章