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


小唯快跑啊
浏览 858回答 3
3回答

BIG阳

我使用自定义视图完成了此操作。设置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);  }}

海绵宝宝撒

最后,我手动生成了尺寸,效果很好: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 drawingaddView(mainImageView,new LinearLayout.LayoutParams(         width, height));
打开App,查看更多内容
随时随地看视频慕课网APP