android用户头像选择(相册,相机拍照)进行裁剪显示
说明:新建项目把如下代码直接负责到自己的项目中运行
第一步: 使用的是一个第三方开源框架 takephoto_library
在build.gradle中添加
implementation 'com.jph.takephoto:takephoto_library:4.0.3'
implementation 'com.android.support:design:27.1.0'
第二步:献上完整代码复制就可以使用
-
MainActivity.java 文件代码
package com.haichenyi.mytakephoto; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.design.widget.BottomSheetDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.jph.takephoto.model.TImage; import java.io.File; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private BottomSheetDialog sheetDialog; ImageView mIII ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = findViewById(R.id.btn); mIII = findViewById(R.id.iiiii); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(); } }); } /** *该方法是从底部弹出对话框 */ private void showDialog() { sheetDialog = new BottomSheetDialog(this); View view = LayoutInflater.from(this).inflate(R.layout.layout_take_photo, null); TextView tvCamera = view.findViewById(R.id.tvCamera); tvCamera.setOnClickListener(this); TextView tvPhoto = view.findViewById(R.id.tvPhoto); tvPhoto.setOnClickListener(this); TextView tvMut = view.findViewById(R.id.tvMut); tvMut.setOnClickListener(this); TextView tvCancel = view.findViewById(R.id.tvCancel); tvCancel.setOnClickListener(this); sheetDialog.setContentView(view); sheetDialog.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) return; if (requestCode == 101) { String data1 = data.getStringExtra("data"); Log.v("wht获取返回的图片路径--1", data1); } else if (requestCode == 102) { String data1 = data.getStringExtra("data"); Log.v("wht获取返回的图片路径--2", data1); sss(data1); } else if (requestCode == 103) { ArrayList<? extends TImage> data3 = data.getParcelableArrayListExtra("data"); // ArrayList<TImage> data1 = (ArrayList<TImage>) data.getParcelableArrayListExtra("data"); Log.v("wht--3", data3.size() + ""); } } /** *获取到处理好的图片路径显示到ImageView控件上 */ private void sss(String path){ File file = new File(path); if(file.exists()){ Bitmap bm = BitmapFactory.decodeFile(path); mIII.setImageBitmap(bm); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tvCamera: startActForResult(1, 101); sheetDialogDismiss(); break; case R.id.tvPhoto: startActForResult(2, 102); sheetDialogDismiss(); break; case R.id.tvMut: startActForResult(3, 103); sheetDialogDismiss(); break; case R.id.tvCancel: sheetDialogDismiss(); break; } } private void startActForResult(int flag, int requestCode) { startActivityForResult(new Intent(MainActivity.this, TakePhotoActivity.class).putExtra("flag", flag), requestCode); } private void sheetDialogDismiss() { if (null != sheetDialog && sheetDialog.isShowing()) { sheetDialog.dismiss(); } } }
-
新建TakePhotoActivity.java类 继续
package com.haichenyi.mytakephoto; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.jph.takephoto.app.TakePhoto; import com.jph.takephoto.app.TakePhotoImpl; import com.jph.takephoto.compress.CompressConfig; import com.jph.takephoto.model.CropOptions; import com.jph.takephoto.model.InvokeParam; import com.jph.takephoto.model.TContextWrap; import com.jph.takephoto.model.TImage; import com.jph.takephoto.model.TResult; import com.jph.takephoto.permission.InvokeListener; import com.jph.takephoto.permission.PermissionManager; import com.jph.takephoto.permission.TakePhotoInvocationHandler; import java.io.File; import java.util.ArrayList; public class TakePhotoActivity extends AppCompatActivity implements TakePhoto.TakeResultListener, InvokeListener { private TakePhoto takePhoto; private InvokeParam invokeParam; private int flag; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { getTakePhoto().onCreate(savedInstanceState); super.onCreate(savedInstanceState); flag = getIntent().getIntExtra("flag", 0); File file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".png"); Uri uri = Uri.fromFile(file); int size = Math.min(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels); CropOptions cropOptions = new CropOptions.Builder().setOutputX(size).setOutputX(size).setWithOwnCrop(false).create(); if (flag == 1) { Log.v("wht", "flag :" + flag); //相机获取照片并剪裁 takePhoto.onPickFromCaptureWithCrop(uri, cropOptions); //相机获取不剪裁 //takePhoto.onPickFromCapture(uri); } else if (flag == 2) { //相册获取照片并剪裁 takePhoto.onPickFromGalleryWithCrop(uri, cropOptions); //相册获取不剪裁 // takePhoto.onPickFromGallery(); } else if (flag == 3) { //多选,并剪裁 takePhoto.onPickMultipleWithCrop(9, cropOptions); //多选,不剪裁 // takePhoto.onPickMultiple(9); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { getTakePhoto().onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); } @Override protected void onSaveInstanceState(Bundle outState) { getTakePhoto().onSaveInstanceState(outState); super.onSaveInstanceState(outState); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); //以下代码为处理Android6.0、7.0动态权限所需 PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults); PermissionManager.handlePermissionsResult(this, type, invokeParam, this); } @Override public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) { PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod()); if (PermissionManager.TPermissionType.WAIT.equals(type)) { this.invokeParam = invokeParam; } return type; } public TakePhoto getTakePhoto() { if (takePhoto == null) { takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this)); } //设置压缩规则,最大500kb //setMaxPixel(100)设置裁剪图片的大小 takePhoto.onEnableCompress(new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(100).create(), true); return takePhoto; } @Override public void takeSuccess(TResult result) { if (flag != 3) { String compressPath = result.getImage().getCompressPath(); setResult(Activity.RESULT_OK, new Intent().putExtra("data", null != compressPath ? compressPath : result.getImage().getOriginalPath())); Log.v("wht", "compressPath:" + compressPath); Log.v("wht", "OriginalPath:" + result.getImage().getOriginalPath()); } else { ArrayList<TImage> images = result.getImages(); setResult(Activity.RESULT_OK, new Intent().putExtra("data", images)); } finish(); } @Override public void takeFail(TResult result, String msg) { Log.v("wht", "takeFail:" + msg); if (flag != 3) { setResult(Activity.RESULT_OK, new Intent().putExtra("data", "")); } else { setResult(Activity.RESULT_OK, new Intent().putExtra("data", new ArrayList())); } finish(); } @Override public void takeCancel() { Log.v("wht", getResources().getString(R.string.msg_operation_canceled)); if (flag != 3) { setResult(Activity.RESULT_OK, new Intent().putExtra("data", "")); } else { setResult(Activity.RESULT_OK, new Intent().putExtra("data", new ArrayList())); } finish(); } }
-
如果需要显示圆形的头像框或其他形状的可以使用 Roundedimageview
添加 implementation 'com.makeramen:roundedimageview:2.3.0'
4.显示头像的布局文件如下:
这个是圆形的
<com.makeramen.roundedimageview.RoundedImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/iv_avatar"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@mipmap/head_portrait"
app:riv_border_color="#333333"
app:riv_border_width="2dip"
app:riv_mutate_background="true"
app:riv_oval="true"
app:riv_tile_mode="repeat"
app:riv_corner_radius="30dip"
android:layout_centerInParent="true"
/>
-
备注说明,如果是7.0及以上版本的手机,调用系统照相机时需要做如下操作
1,AndroidManifest.xml文件里还需要加入这段: <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider> 2,在res目录下创建xml文件夹,在xml文件夹中新建file_path.xml文件,代码如下: <?xml version="1.0" encoding="utf-8"?> <resources> <paths> <!--name 是起的别名(随便起) path是要共享的文件夹 --> <external-path name="files_root" path="Android/data/com.ele.lookover/" /> <external-path name="/storage/emulated/0/" path="." /> </paths> </resources>