【问题标题】:how do I set a minimum scalable value for a ImageView?如何为 ImageView 设置最小可扩展值?
【发布时间】:2019-02-07 13:19:33
【问题描述】:

假设我的可绘制文件夹中有一个分辨率为 400x400 的图像“A”,我将 ImageView 源设置为 A,此 ImageView 位于线性布局或卡片布局内。

我希望图像根据设备进行缩放,对于 4 英寸设备,我希望它是 120dp X 120dp,但我希望它根据显示器的尺寸缩放到更大的像素

【问题讨论】:

  • 你可以在 ImageView 中使用 LinearLayout + weight 和 scale 类型的 fitCenter,或者使用一些 ConstraintLayout 魔法(肯定会更好,但我不知道如何使用它)

标签: android android-studio imageview android-imageview scale


【解决方案1】:

首先,你需要得到你设备的分辨率,这样做是这样的:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;

然后,根据宽度和高度,可以通过一定的语句来设置ImageView.SetWidth(...) / Height / ScaleType。

【讨论】:

  • 是这样做更好还是在这些文件夹中为较低 dpi 制作新布局更好res/layout-w600dp/main_activity.xml res/layout-large/main_activity.xml res/layout-xlarge/main_activity.xml
【解决方案2】:

通过使用约束布局并将图像宽度和高度设置为 0dp 以使其根据图像源大小进行缩放来解决此问题。

【讨论】:

    【解决方案3】:

    在 ImageView centerInside 中使用 ScaleType。

    或者

    您可以通过维护Aspect Ratio来根据屏幕大小新建Bitmap

    假设您的图像尺寸为 400x300 (WxH)

    而您预期的ImageView 大小为 200x400

    如果你想根据ImageView的宽度来适应它,那么你将使用下面的公式计算新的HeightWidth,并调整新的Bitmap的大小。

    纵横比 = 高度 / 宽度(如果我们采用新宽度)

    纵横比 = 宽度/高度(如果我们采用新高度)

    AR= 300/400 = 0.75

    New Height = NewWidth * AR;
    NewHeight = 200 * 0.75;
    NewHeight = 150 ;
    

    因此,您可以调整位图的大小,如采用上述高度和宽度。

    Online Image Aspect Ratio Calculator

    使用以下方法调整位图大小:

    public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
    Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    Matrix m = new Matrix();
    m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
    canvas.drawBitmap(bitmap, m, new Paint());
    return output;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2018-05-01
      相关资源
      最近更新 更多