将 ImageView 的比例保持在 Android

Keeping ratio of ImageView in Android

我必须设置 ImageView 的背景图片,然后设置此 ImageView 的 imageSource。

所以我所做的是使用 setBackgroundImage() 设置图像视图背景。 我也设置 adjustViewBounds = truescaleType = "fitCenter",以及 height = 55dpwidth = wrap content

所以我第一次(当我只设置背景时)预计会有这种情况 - 视图将具有相同的比例并且适合最小的宽度或高度(当然如果高度大于 55dp ,它将被缩放)。但结果是缩放图像(当图像应大于 55 dp,即缩放高度)。图像位于 RelativeLayout 中。不幸的是,我无法 post 整个代码。

提前致谢。

您必须子类化 ImageView 并覆盖 onLayout() 以保持 width/height 比率,如下所示:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    double ratio = ...

    int width = right - left;
    int height = ratio * width;
    ViewGroup.LayoutParams params = this.getLayoutParams();
    params.height = height;
    params.width = width;
    this.setLayoutParams(params);
    this.setMeasuredDimension(width, height);
    super.onLayout(changed, left, top, right, top + height);
}