android 详细讲解 高仿QQ弹出popwindow调用系统相机拍摄裁剪并预览设置图像

MainActivity布局,设置一个默认图片,模拟QQ头像


<?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"
    android:id="@+id/line"
    android:layout_marginTop="30dp"
    tools:context="com.example.shangchuanimg.MainActivity">

    <ImageView
        android:layout_gravity="center_horizontal"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/img"
     android:src="@mipmap/ic_launcher"/>
</LinearLayout>

给头像设置监听时间,点击弹出popwindow,长按查看大图。接下来我们看popwindow的动画页面,从底部往上弹出。创建文件夹anim,里面创建一个popwindow弹出的布局和一个消失的布局。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <!--这个是弹出的布局-->
    <translate
        android:duration="500"
        android:fromYDelta="0"
        android:toYDelta="100%p" />
    
</set>

以下是popwindow消失的布局

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <!--这个是消失的布局-->
    <translate
        android:duration="500"
        android:fromYDelta="100%p"
        android:toYDelta="0" />
</set>

然后我们需要在res-->values-->styles里面配置动画

 <style name="mypopwindow_anim_style">
        <item name="android:windowEnterAnimation">@anim/set_in</item>
       
        <item name="android:windowExitAnimation">@anim/set_out</item>
       
    </style>

这时候需要在另一个pop.xml中设置popwindow 的内容,即三个Button按钮,拍照、从相册选择、消失。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_xiangce"
        android:text="从相册选取"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_quxiao"
        android:text="取消"/>

</LinearLayout>

接下来我们就可以在MainActivity中写代码了,

package com.example.shangchuanimg;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private ImageView img;
    private LinearLayout line;
    private File tempFile = new File(Environment.getExternalStorageDirectory(),
            getPhotoFileName());

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
    }

    private void initListener() {

        img.setOnClickListener(new View.OnClickListener() {

            private Button btn_quxiao;
            private Button btn_xiangce;
            private Button btn_paizhao;

            @Override
            public void onClick(View v) {

                View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop, null);
                btn_paizhao = inflate.findViewById(R.id.btn_paizhao);
                btn_quxiao = inflate.findViewById(R.id.btn_quxiao);
                btn_xiangce = inflate.findViewById(R.id.btn_xiangce);

                final PopupWindow popupWindow = new PopupWindow(inflate, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                popupWindow.showAtLocation(line, Gravity.BOTTOM, 0, 0);

                btn_paizhao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //启动相机程序
                        Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(tempFile));
                        startActivityForResult(cameraintent, PHOTO_REQUEST_TAKEPHOTO);

                    }
                });

                btn_quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        popupWindow.dismiss();
                    }
                });

                btn_xiangce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //使用Intent  意图
                        Intent intent = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 2);

                        popupWindow.dismiss();
                    }
                });

            }
        });

        img.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(tempFile), "image/*"); //告诉系统这是个image类型 调用相应的预览
                startActivity(intent);
                return false;
            }
        });
    }


    //Intent  回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //获取图片路径
        if (requestCode == 2 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            c.close();

            showImage(imagePath);
        }

        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
                startPhotoZoom(Uri.fromFile(tempFile));
                break;
            case PHOTO_REQUEST_GALLERY:// 当选择从本地获取图片时
                // 做非空判断,当我们觉得不满意想重新剪裁的时候便不会报异常,下同
                if (data != null)
                    startPhotoZoom(data.getData());
                break;
            case PHOTO_REQUEST_CUT:// 返回的结果
                if (data != null)
                    // setPicToView(data);
                    sentPicToNext(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    // 将进行剪裁后的图片传递到下一个界面上
    private void sentPicToNext(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            if (photo == null) {
                img.setImageResource(R.mipmap.ic_launcher);
            } else {
                img.setImageBitmap(photo);
//
            }

            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] photodata = baos.toByteArray();
                System.out.println(photodata.toString());
                // Intent intent = new Intent();
                // intent.setClass(RegisterActivity.this, ShowActivity.class);
                // intent.putExtra("photo", photodata);
                // startActivity(intent);
                // finish();
            } catch (Exception e) {
                e.getStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";

    }


    //加载图片
    private void showImage(String imaePath) {

        Bitmap bitmap = BitmapFactory.decodeFile(imaePath);
        img.setImageBitmap(bitmap);
    }


    private void initView() {
        img = (ImageView) findViewById(R.id.img);
        line = (LinearLayout) findViewById(R.id.line);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值