本文共 2283 字,大约阅读时间需要 7 分钟。
在Android开发中,我们需要实现用户点击图片时触发的操作,例如从相册或相机选择图片作为头像。以下将详细阐述一个典型实现方案。
View.OnClickListener itemsOnClick = new View.OnClickListener() { public void onClick(View v) { // 消除弹出窗口 menuWindow.dismiss(); switch (v.getId()) { case R.id.btn_take_photo: // 启动相机拍摄 choseHeadImageFromCameraCapture(); break; case R.id.btn_pick_photo: // 从本地相册选择图片 choseHeadImageFromGallery(); break; } }};
确保设备具备SD存储卡是实现图片存储的前提条件。
public static boolean hasSdcard() { String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED);}
创建一个意图,指定图片文件类型,并启动图像选择器。
private void choseHeadImageFromGallery() { Intent intentFromGallery = new Intent(); intentFromGallery.setType("image/*"); intentFromGallery.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);}
设置相机拍摄参数并启动相机应用。
private void choseHeadImageFromCameraCapture() { Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (hasSdcard()) { intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(Environment.getExternalStorageDirectory(),_IMAGE_FILE_NAME) )); } startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);}
根据设置的宽高比例对图片进行裁剪操作。
public void cropRawPhoto(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", output_X); intent.putExtra("outputY", output_Y); intent.putExtra("return-data", true); startActivityForResult(intent, CODE_RESULT_REQUEST);}
将剪裁后的图片数据加载到头像视图中。
private void setImageToHeadView(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); iv_head.setImageBitmap(photo); }}
这个方案全面覆盖了从点击事件触发的所有必要操作,确保图片选择过程的流畅性和稳定性。
转载地址:http://rddgz.baihongyu.com/