ImageView使用(适屏、缩放功能)

1、适屏

提取手机的图片库,并且进行选择图片的功能:

Button onClick:
Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 打开手机的图片库
            startActivityForResult(intent, IMAGE_SELECT);

处理图片,按照手机的屏幕大小显示:

if (requestCode == IMAGE_SELECT) {
                Uri url = data.getData();// 获得图片的路径
                int dw = getWindowManager().getDefaultDisplay().getWidth();// 获得屏幕的宽度
                int dh = getWindowManager().getDefaultDisplay().getWidth() / 2;// 获得屏幕的高度/2
                try {
                    /**
                     * BitampFactory :可以创建一个Bitmap位图对象
                     * BitampFactory.Options为匿名内部类
                     */
                    // 实现对图片的裁剪的类,是一个匿名内部类
                    BitmapFactory.Options factory = new BitmapFactory.Options();
                    factory.inJustDecodeBounds = true;// 如果设置为true,允许查询图片不是按照像素分配给内存
                    // 将一个流转换为Bitmap位图对象
                    Bitmap bmp = BitmapFactory.decodeStream(
                            getContentResolver().openInputStream(url), null,
                            factory);
                    // 对图片的宽度和高度对应手机的屏幕进行匹配
                    int hRatio = (int) Math
                            .ceil(factory.outHeight / (float) dh);
                    // 如果大于1 表示图片的高度大于手机屏幕的高度
                    int wRatio = (int) Math.ceil(factory.outWidth / (float) dw);
                    // 如果大于1表示图片的宽度大于手机屏幕的宽度
                    // 缩放到1/radio的尺寸 和1/radio^2像素
                    if (hRatio > 1 || wRatio > 1) {
                        if (hRatio > wRatio) {
                            factory.inSampleSize = hRatio;
                        } else {
                            factory.inSampleSize = wRatio;
                        }
                    }

                    factory.inJustDecodeBounds = false;
                    // 使用BitmapFactory对图片进行适屏的操作
                    bmp = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(url), null, factory);
                    imageView.setImageBitmap(bmp);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }

2、缩放:

    Intent intent2 = getImageClipIntent();
            startActivityForResult(intent2, IMAGE_CUT);
 if (requestCode == IMAGE_CUT) {
                Bitmap bitmap = data.getParcelableExtra("data");
                imageView.setImageBitmap(bitmap);
            }

 

posted @ 2014-08-09 16:58  转身就是一辈子  阅读(1390)  评论(0编辑  收藏  举报