欢迎光临
我们一直在努力

由 ImageView 获取到的 Drawable 对象,它的 intrinsicWidth、intrinsicWidth 与实际图片的尺寸

<ImageView
android:id="@+id/iv_test"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/test" />

ImageView ivTest = findViewById(R.id.iv_test);

int width = ivTest.getWidth();
int height = ivTest.getHeight();

Drawable drawable = ivTest.getDrawable();

int intrinsicWidth = drawable.getIntrinsicWidth();
int intrinsicHeight = drawable.getIntrinsicHeight();

Log.i(TAG, "width: " + width);
Log.i(TAG, "height: " + height);

Log.i(TAG, "intrinsicWidth: " + intrinsicWidth);
Log.i(TAG, "intrinsicHeight: " + intrinsicHeight);

# 输出结果

width: 200
height: 200
intrinsicWidth: 845
intrinsicHeight: 845

  • 在 Android 开发中,由 ImageView 获取到 Drawable 对象

  • Drawable 对象的 intrinsicWidth 与 intrinsicWidth 为 845 * 845,实际图片的尺寸为 634 * 634

  • 问题解读
  • intrinsicWidth 与 intrinsicHeight 是 Drawable 对象的固有尺寸,即图片 @mipmap/test 的原始尺寸

  • 但实际图片的尺寸为 634 * 634,而 Android 系统会根据设备的密度进行缩放,以适应不同的屏幕

  • 密度类型密度值缩放比例目录后缀
    ldpi 120dpi 0.75x -ldpi
    mdpi 160dpi 1.0x -mdpi
    hdpi 240dpi 1.5x -hdpi
    xhdpi 320dpi 2.0x -xhdpi
    xxhdpi 480dpi 3.0x -xxhdpi
    xxxhdpi 640dpi 4.0x -xxxhdpi
  • @mipmap/test 存放在 mipmap-hdpi 目录下,而设备的密度如下
  • DisplayMetrics metrics = getResources().getDisplayMetrics();

    float density = metrics.density;
    int densityDpi = metrics.densityDpi;

    Log.i(TAG, "density: " + density);
    Log.i(TAG, "densityDpi: " + densityDpi);

    # 输出结果

    density: 2.0
    densityDpi: 320

  • 根据设备的密度值为 320、缩放比例为 2.0x 进行计算
  • # 使用密度值计算

    缩放因子 = 设备密度值 / 资源密度值 = 320 / 240 = 1.333…
    报告尺寸 = 634 × 1.333… ≈ 845px

    # 使用缩放比例计算

    缩放因子 = 设备缩放比例 / 资源缩放比例 = 2.0 / 1.5 = 1.333…
    报告尺寸 = 634 × 1.333… ≈ 845px

    赞(0)
    未经允许不得转载:171主机测评 » 由 ImageView 获取到的 Drawable 对象,它的 intrinsicWidth、intrinsicWidth 与实际图片的尺寸
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址