1,点击按钮,指定action和uri,设定结果码(ResultCode).到达手机默认相册的Gallery.
代码如下:
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent(Intent.ACTION_PICK,
- android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 启动照片Gallery
- startActivityForResult(intent, 0);
- }
2,选择图片,返回所选照片uri信息
代码如下:
- @Override
- protected void onActivityResult(int requestCode, int resultCode,
- Intent intent) {
- // TODO Auto-generated method stub
- super.onActivityResult(requestCode, resultCode, intent);
- if (resultCode == RESULT_OK) {// 操作成功
- Uri imgFileUri = intent.getData();// 获得所选照片的信息
3,处理图片,设定合适的尺寸(正好适应屏幕)
设定BitmapFactory.Options 参数inJustDecodeBounds = true,即不创建bitmap,但可获取bitmap的相关属性。以宽高比例差距 最大者为基准。
代码如下:
- // 由于返回的图像可能太大而无法完全加载到内存中。系统有限制,需要处理。
- Display currentDisplay = getWindowManager().getDefaultDisplay();
- int defaultHeight = currentDisplay.getHeight();
- int defaultWidth = currentDisplay.getWidth();
- BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
- bitmapFactoryOptions.inJustDecodeBounds = true;// /只是为获取原始图片的尺寸,而不返回Bitmap对象
- // 注上:If set to true, the decoder will return null (no bitmap), but
- // the out... fields will still be set,
- // allowing the caller to query the bitmap without having to
- // allocate the memory for its pixels
- try {
- Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
- .openInputStream(imgFileUri), null,
- bitmapFactoryOptions);
- int outHeight = bitmapFactoryOptions.outHeight;
- int outWidth = bitmapFactoryOptions.outWidth;
- int heightRatio = (int) Math.ceil((float) outHeight
- / defaultHeight);
- int widthRatio = (int) Math.ceil((float) outWidth
- / defaultWidth);
- if (heightRatio > 1 || widthRatio > 1) {
- if (heightRatio > widthRatio) {
- bitmapFactoryOptions.inSampleSize = heightRatio;
- } else {
- bitmapFactoryOptions.inSampleSize = widthRatio;
- }
- }
4,inJustDecodeBounds = false,创建将此bitmap赋给第一个ImageView。
代码如下:
- bitmapFactoryOptions.inJustDecodeBounds = false;
- bitmap = BitmapFactory.decodeStream(getContentResolver()
- .openInputStream(imgFileUri), null,
- bitmapFactoryOptions);
- mImageShow.setImageBitmap(bitmap);
5,绘制bitmap(选中的图片),赋给第二个ImageView
a, 绘制正面Bitmap
b,在此Bitmap上绘制文本
c,创建Matrix对象,指定旋转角度。
d,创建新的bitmap对象,即canvas即将要绘制的倾斜区域
e,绘制
代码如下:
- // /*
- // * 在位图上绘制位图
- // */
- //
- Bitmap bitmapAltered = Bitmap.createBitmap(bitmap.getWidth(),
- bitmap.getHeight(), bitmap.getConfig());
- Canvas canvas = new Canvas(bitmapAltered);// bitmap提供了画布,只在此提供了大小尺寸,偏移后并未有背景显示出来
- Paint paint = new Paint();
- canvas.drawBitmap(bitmap, 0, 0, paint);
- paint.setColor(Color.RED);
- canvas.drawText("hello", 10, 10, paint);
- //先绘制正面图片,再旋转
- Matrix matrix = new Matrix();
- matrix.setRotate(45, 0, 0);
- //创建一个倾斜的绘制区域
- Bitmap bitmapRotated = Bitmap.createBitmap(bitmapAltered, 0, 0, bitmapAltered.getWidth(), bitmapAltered.getHeight(), matrix, false);
- canvas.drawBitmap(bitmapAltered, matrix, paint);
- mImageAltered.setImageBitmap(bitmapRotated);