一尘不染

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

java

我想下载一个图像(大小不明,但始终大致为正方形)并显示它,以便它在任何屏幕尺寸上都水平填充屏幕,并垂直拉伸以保持图像的纵横比。这是我的(无效)代码。它水平拉伸图像,但不垂直拉伸图像,因此将其压扁…

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));

阅读 472

收藏
2020-03-21

共1个答案

一尘不染

我使用自定义视图完成了此操作。设置layout_width =“ fill_parent”和layout_height =“ wrap_content”,并将其指向适当的可绘制对象:

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);
  }
}
2020-03-21