Android:如何在保持宽高比的同时将图像拉伸到屏幕宽度?

fre*_*ley 118 java layout android

我想下载一个图像(大小未知,但总是大致正方形)并显示它以使其水平填充屏幕,并垂直拉伸以保持图像的宽高比,在任何屏幕尺寸上.这是我的(非工作)代码.它水平拉伸图像,但不垂直,因此被压扁...

ImageView mainImageView = new ImageView(context);
    mainImageView.setImageBitmap(mainImage); //downloaded from server
    mainImageView.setScaleType(ScaleType.FIT_XY);
    //mainImageView.setAdjustViewBounds(true); 
    //with this line enabled, just scales image down
    addView(mainImageView,new LinearLayout.LayoutParams( 
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
Run Code Online (Sandbox Code Playgroud)

Bob*_*Lee 132

我用自定义视图完成了这个.设置layout_width ="fill_parent"和layout_height ="wrap_content",并将其指向适当的drawable:

public class Banner extends View {

  private final Drawable logo;

  public Banner(Context context) {
    super(context);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

  public Banner(Context context, AttributeSet attrs) {
    super(context, attrs);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

  public Banner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    logo = context.getResources().getDrawable(R.drawable.banner);
    setBackgroundDrawable(logo);
  }

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

  • 我无法相信在iOS和Windows Phone上轻松操作是多么困难. (44认同)
  • 谢谢!!这应该是正确的答案!:)我在这篇文章中调整了这个以获得更多的灵活性:http://stackoverflow.com/questions/4677269/how-to-stretch-three-images-across-the-screen-preserving-aspect-ratio我使用一个ImageView所以可以在XML中设置drawable或者像代码中的普通ImageView一样使用它来设置图像.效果很好! (12认同)

fre*_*ley 24

最后,我手动生成了尺寸,效果很好:

DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = width * mainImage.getHeight() / mainImage.getWidth(); //mainImage is the Bitmap I'm drawing
addView(mainImageView,new LinearLayout.LayoutParams( 
        width, height));
Run Code Online (Sandbox Code Playgroud)


Tim*_*mmm 21

我只是阅读了源代码,ImageView如果不使用此线程中的子类化解决方案,基本上是不可能的.在ImageView.onMeasure我们得到这些线:

        // Get the max possible width given our constraints
        widthSize = resolveAdjustedSize(w + pleft + pright, mMaxWidth, widthMeasureSpec);

        // Get the max possible height given our constraints
        heightSize = resolveAdjustedSize(h + ptop + pbottom, mMaxHeight, heightMeasureSpec);
Run Code Online (Sandbox Code Playgroud)

图像的尺寸在哪里hw是,并且p*是填充.

然后:

private int resolveAdjustedSize(int desiredSize, int maxSize,
                               int measureSpec) {
    ...
    switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            /* Parent says we can be as big as we want. Just don't be larger
               than max size imposed on ourselves.
            */
            result = Math.min(desiredSize, maxSize);
Run Code Online (Sandbox Code Playgroud)

因此,如果你有一个layout_height="wrap_content"它将设置widthSize = w + pleft + pright,或换句话说,最大宽度等于图像宽度.

这意味着除非您设置精确的尺寸,否则图像永远不会放大.我认为这是一个错误,但祝谷歌注意或修复它.编辑:吃我自己的话,我提交了一个错误报告,他们说它已在未来版本中得到修复!

另一种方法

这是另一个子类化解决方法,但你应该(理论上,我还没有真正测试过它!)能够在任何地方使用它ImageView.使用它设置layout_width="match_parent",和layout_height="wrap_content".它比通常的解决方案更加通用.例如,你可以适应高度和宽度.

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

// This works around the issue described here: http://stackoverflow.com/a/12675430/265521
public class StretchyImageView extends ImageView
{

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

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // Call super() so that resolveUri() is called.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // If there's no drawable we can just use the result from super.
        if (getDrawable() == null)
            return;

        final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);

        int w = getDrawable().getIntrinsicWidth();
        int h = getDrawable().getIntrinsicHeight();
        if (w <= 0)
            w = 1;
        if (h <= 0)
            h = 1;

        // Desired aspect ratio of the view's contents (not including padding)
        float desiredAspect = (float) w / (float) h;

        // We are allowed to change the view's width
        boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;

        // We are allowed to change the view's height
        boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;

        int pleft = getPaddingLeft();
        int pright = getPaddingRight();
        int ptop = getPaddingTop();
        int pbottom = getPaddingBottom();

        // Get the sizes that ImageView decided on.
        int widthSize = getMeasuredWidth();
        int heightSize = getMeasuredHeight();

        if (resizeWidth && !resizeHeight)
        {
            // Resize the width to the height, maintaining aspect ratio.
            int newWidth = (int) (desiredAspect * (heightSize - ptop - pbottom)) + pleft + pright;
            setMeasuredDimension(newWidth, heightSize);
        }
        else if (resizeHeight && !resizeWidth)
        {
            int newHeight = (int) ((widthSize - pleft - pright) / desiredAspect) + ptop + pbottom;
            setMeasuredDimension(widthSize, newHeight);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 显然我必须吃掉我的话 - 他们说它已经在未来的版本中修复了! (3认同)

小智 17

将adjustViewBounds设置为true并使用LinearLayout视图组对我来说非常有效.无需子类或询问设备指标:

//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);
Run Code Online (Sandbox Code Playgroud)


小智 13

对于AGES,我一直在以这种或那种形式为这个问题苦苦挣扎,谢谢,谢谢,谢谢.... :)

我只是想指出,你可以通过扩展View和覆盖onMeasure从Bob Lee的工作中获得一个可推广的解决方案.这样你可以将它用于你想要的任何可绘制的,如果没有图像它就不会破坏:

    public class CardImageView extends View {
        public CardImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

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

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

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            Drawable bg = getBackground();
            if (bg != null) {
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
                setMeasuredDimension(width,height);
            }
            else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 在这个问题的所有许多解决方案中,这是第一个只是一个插入式解决方案,其他的总是有缺点(就像在没有代码重写的情况下无法在运行时更改图像).谢谢! (2认同)

Fat*_*tie 10

在某些情况下,这个神奇的公式可以很好地解决问题.

对于那些在另一个平台上苦苦挣扎的人来说,"尺寸和形状适合"选项在Android中得到了很好的处理,但很难找到.

您通常需要这种组合:

  • 宽度匹配父,
  • 高度包装内容,
  • adjustViewBounds开启(原文如此)
  • scale fitCenter
  • cropToPadding OFF(原文如此)

然后它是自动和惊人的.

如果你是一个iOS开发者,你可以在表格视图中完成"完全动态的单元格高度",这真是太神奇了.错误,我的意思是ListView.请享用.

<com.parse.ParseImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/post_image"
    android:src="@drawable/icon_192"
    android:layout_margin="0dp"
    android:cropToPadding="false"
    android:adjustViewBounds="true"
    android:scaleType="fitCenter"
    android:background="#eff2eb"/>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 5

我在LinearLayout中使用这些值完成了它:

Scale type: fitStart
Layout gravity: fill_horizontal
Layout height: wrap_content
Layout weight: 1
Layout width: fill_parent
Run Code Online (Sandbox Code Playgroud)


Nei*_*lDA 5

我已经设法使用此XML代码实现此目的.可能是这样的情况,日食不会使高度显示它扩展到适合; 但是,当您在设备上实际运行它时,它会正确呈现并提供所需的结果.(至少对我而言)

<FrameLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

     <ImageView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:adjustViewBounds="true"
          android:scaleType="centerCrop"
          android:src="@drawable/whatever" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)


Sin*_*Þór 5

每个人都在做这个程序,所以我认为这个答案在这里完全适合.这段代码适用于我的xml.我还没考虑比率,但是如果能帮助任何人,仍然想要这个答案.

android:adjustViewBounds="true"
Run Code Online (Sandbox Code Playgroud)

干杯..