调整ImageView的大小以适应宽高比

Muz*_*Muz 12 android imageview

我需要调整ImageView的大小以使其适合屏幕,保持相同的宽高比.以下条件成立:

  • 图像是固定宽度(屏幕宽度的大小)
  • 图像从因特网下载,即尺寸只能在以后确定
  • 每幅图像的宽高比会有所不同; 有些是高的,有些是方形的,有些是扁平的
  • ImageView的高度需要根据宽高比的变化而变大或变小
  • 裁剪过多的高度,默认情况下不能有很多空的空间.

例如,400像素宽屏幕上的小型50x50图像会将图像缩放到400x400像素.800x200图像将缩放到400x100.

我已经查看了大多数其他线程,并且许多提议的解决方案就像简单地更改adjustViewBounds并且scaleType只会缩小图像,而不是扩展它.

Aks*_*wal 24

我在这篇文章中借助Bob Lee的答案创建了它:Android:如何在保持纵横比的同时将图像拉伸到屏幕宽度?

package com.yourpackage.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AspectRatioImageView extends ImageView {

    public AspectRatioImageView(Context context) {
        super(context);
    }

    public AspectRatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在XML中使用它:

<com.yourpackage.widgets.AspectRatioImageView android:layout_centerHorizontal="true"
    android:src="@drawable/yourdrawable" android:id="@+id/image"
    android:layout_alignParentTop="true" android:layout_height="wrap_content"
    android:layout_width="match_parent" android:adjustViewBounds="true" />
Run Code Online (Sandbox Code Playgroud)

玩得开心!

  • +1,好看又简单,只有我会保护它免受`getIntrinsicWidth`为0(它会崩溃试图除以它) (4认同)

Muz*_*Muz 11

ImageView mImageView; // This is the ImageView to change

// Use this in onWindowFocusChanged so that the ImageView is fully loaded, or the dimensions will end up 0.
public void onWindowFocusChanged(boolean hasFocus) 
{
    super.onWindowFocusChanged(hasFocus);

    // Abstracting out the process where you get the image from the internet
    Bitmap loadedImage = getImageFromInternet (url);

    // Gets the width you want it to be
    intendedWidth = mImageView.getWidth();

    // Gets the downloaded image dimensions
    int originalWidth = loadedImage.getWidth();
    int originalHeight = loadedImage.getHeight();

    // Calculates the new dimensions
    float scale = (float) intendedWidth / originalWidth;
    int newHeight = (int) Math.round(originalHeight * scale);

    // Resizes mImageView. Change "FrameLayout" to whatever layout mImageView is located in.
    mImageView.setLayoutParams(new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT));
    mImageView.getLayoutParams().width = intendedWidth;
    mImageView.getLayoutParams().height = newHeight;
}
Run Code Online (Sandbox Code Playgroud)