Android 在自动旋转上缩放图像视图

Android 在自动旋转上缩放图像视图,android,android-layout,android-imageview,autoscaling,screen-rotation,Android,Android Layout,Android Imageview,Autoscaling,Screen Rotation,我正在获取一个url并在Imageview中显示它。我的设备的自动漫游已打开。我希望imageview在旋转后根据设备的宽度进行缩放 当我从url获取图像时,是否有可能?如果图像被调整到看起来不正确的位置,或者您只是想更多地控制旋转中发生的事情,您也可以在代码中执行此操作 首先获取设备的宽度和高度: Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize

我正在获取一个url并在Imageview中显示它。我的设备的自动漫游已打开。我希望imageview在旋转后根据设备的宽度进行缩放


当我从url获取图像时,是否有可能?如果图像被调整到看起来不正确的位置,或者您只是想更多地控制旋转中发生的事情,您也可以在代码中执行此操作

首先获取设备的宽度和高度:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
然后可以使用该信息调整图像大小

您可以设置
o.inJustDecodeBounds=true
以获得图像大小,而无需加载图像。如果图像太大,可以调整其大小。下面是示例代码

private Bitmap getBitmap(String path) {

    Uri uri = getImageUri(path);
    InputStream in = null;
    try {
        final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
        in = mContentResolver.openInputStream(uri);

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, o);
        in.close();

        int scale = 1;
        while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
            scale++;
        }
        Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

        Bitmap b = null;
        in = mContentResolver.openInputStream(uri);

        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
            b = BitmapFactory.decodeStream(in, null, o);

            // resize to desired dimensions
            int height = b.getHeight();
            int width = b.getWidth();
            Log.d(TAG, "1th scale operation dimenions - width: " + width + ", height: " + height);

            double y = Math.sqrt(IMAGE_MAX_SIZE / (((double) width) / height));
            double x = (y / height) * width;

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, (int) y, true);
            b.recycle();
            b = scaledBitmap;

            System.gc();

        } else {
            b = BitmapFactory.decodeStream(in);
        }
        in.close();

        Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " + b.getHeight());
        return b;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(),e);
        return null;
    }
}

将imageview width参数设置为将_parent和scaleType匹配为fitXYit正在拉伸我的图像如果该缩放类型不适用于您,因为您希望保持纵横比,请查看此项如果该缩放类型也不适用,您必须自己进行缩放;)