Demo源码位置:http://git.oschina.net/zj2012zy/Android-Demo/tree/master/AndroidDemo/headset
一般需要用户信息的好多的也需要设置用户头像,通常设置用户头像的操纵要么从手机选择一张图片,要么直接通过手机拍照进行设置。示意图如下:
另外:制作手机的动态截屏,可以使用应用宝的动态截屏功能,非常的方便。
布局文件很简单:就是两个按钮加一个imageview用来显示设置好的头像,就不说了。
核心代码为如下四个函数:
1.选择一张图片
1 public static void selectPhoto(Activity activity) { 2 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 3 intent.setType("image/jpeg"); 4 intent.putExtra("return-data", true); 5 activity.startActivityForResult(intent, PHOTO_PICKED_WITH_DATA); 6 }
2、拍照并存储
1 public static String takePicture(Activity activity) { 2 createDirFile(Environment.getExternalStorageDirectory().getPath() + "/zhaojie/images/"); 3 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 4 String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); 5 String path = Environment.getExternalStorageDirectory().getPath() + "/zhaojie/images/" + timeStamp + ".png"; 6 File file = createNewFile(path); 7 if (file != null) { 8 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); 9 } 10 activity.startActivityForResult(intent, INTENT_REQUEST_CODE_CAMERA); 11 return path; 12 }
3、处理拍照或者是选择的照片,截取头像,其中可指定截取头像的大小。
1 private void cropImageUri(Uri uri, int requestCode) { 2 Intent intent = new Intent("com.android.camera.action.CROP"); 3 intent.setDataAndType(uri, "image/*"); 4 intent.putExtra("crop", "true"); 5 intent.putExtra("aspectX", 1); 6 intent.putExtra("aspectY", 1); 7 intent.putExtra("outputX", 320); 8 intent.putExtra("outputY", 320); 9 intent.putExtra("scale", true); 10 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 11 intent.putExtra("return-data", true); 12 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); 13 intent.putExtra("noFaceDetection", true); // no face detection 14 startActivityForResult(intent, requestCode); 15 }
4、整体流程基本都是通过调用系统activity实现,代码如下
1 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 2 super.onActivityResult(requestCode, resultCode, data); 3 if (resultCode != RESULT_OK) 4 return; 5 Bitmap tempPhoto = null; 6 switch (requestCode) { 7 case PHOTO_PICKED_WITH_DATA: // ???????? 8 ContentResolver cr = this.getContentResolver(); 9 try { 10 Uri uri = data.getData(); 11 cropImageUri(uri, PHOTO_CROP_DATA); 12 // tempPhoto = 13 // BitmapFactory.decodeStream(cr.openInputStream(uri)); 14 // mStepPhoto.setUserPhoto(tempPhoto); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 break; 19 case INTENT_REQUEST_CODE_CAMERA: 20 tempPhoto = BitmapFactory.decodeFile(headPath); 21 cropImageUri(Uri.fromFile(new File(headPath)), PHOTO_CROP_DATA); 22 break; 23 case PHOTO_CROP_DATA: 24 tempPhoto = data.getParcelableExtra("data"); 25 mHead.setImageBitmap(tempPhoto); 26 break; 27 } 28 }
文章从简,具体实现请参考demo,欢迎留言讨论