如何实现Android图像缩放类型以适应宽度和Scaley=ScaleX?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (681)

如何设置为布局或图像视图来缩放图像(以宽度计)以适应屏幕的宽度并以相同的比例缩放高度?

我想要图片中的第二个屏幕:

以下是我的代码:

    Drawable imageDrawable = getResources().getDrawable(imageResource);
    contentContainer.setBackgroundDrawable(imageDrawable);

    Rect rect = imageDrawable.getBounds();
    int originalWidth = rect.width();
    int originalHeight = rect.height();

    Display display = getActivity().getWindowManager().getDefaultDisplay(); 
    int width = display.getWidth();

    int height = originalHeight * (width/originalWidth);

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
    contentContainer.setLayoutParams(layoutParams);


    contentContainer.post(new Runnable() {

        @Override
        public void run() {
            contentContainer.setScaleY(contentContainer.getScaleX());

            Rect rect = contentContainer.getBackground().getBounds();
            int originalWidth = rect.width();
            int originalHeight = rect.height();

            Display display = getActivity().getWindowManager().getDefaultDisplay(); 
            int width = display.getWidth();

            int height = originalHeight * (width/originalWidth);

            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
            contentContainer.setLayoutParams(layoutParams);

        }
    }
提问于
用户回答回答于

使用FrameLayout作为父级,然后添加Imageview作为子视图

用户回答回答于

是否尝试过在布局文件中使用ScaleType?

<ImageView
    ...
    android:scaleType="fitStart"
    />

扫码关注云+社区

领取腾讯云代金券