为什么大于设定尺寸的图像不会缩小

时间:2015-04-02 09:03:43

标签: android imageview rescale

我计算出片段的宽度和高度,并将其图像缩放到该片段的特定百分比。这适用于需要按比例放大以满足该尺寸的图像,但较大的图像似乎忽略了尺度(我认为它们会缩小一点但不会缩小尺寸)。

我通过http asyncTask调用得到我的imahes然后在onPostexecute上设置imageView控件src并缩放imageView。适用于较小的图像,而不是较大的图像。

较大的图像为10kb,较小的图像为1kb。

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
        if (result != null) {
            int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 35, getContext().getResources().getDisplayMetrics());
            int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, 35, getContext().getResources().getDisplayMetrics());

            bmImage.setMinimumWidth(width);
            bmImage.setMinimumHeight(height);
            bmImage.setMaxWidth(width);
            bmImage.setMaxHeight(height);

        }

我看到维度是正确的,然后在imageView中正确设置(最小值和最大值),但是mDrawable attr很大,所以这可能是一个指示设置了什么?

1 个答案:

答案 0 :(得分:0)

https://argillander.wordpress.com/2011/11/24/scale-image-into-imageview-then-resize-imageview-to-match-the-image/

private void scaleImage(ImageView view, int boundBoxInDp)
{
    // Get the ImageView and its bitmap
    Drawable drawing = view.getDrawable();
    Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();

    // Get current dimensions
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    float xScale = ((float) boundBoxInDp) / width;
    float yScale = ((float) boundBoxInDp) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    width = scaledBitmap.getWidth();
    height = scaledBitmap.getHeight();

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}