android - 如何从 ImageView 获取实际图像宽度/高度?

标签 android android-layout android-imageview

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/myImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:background="@android:color/black"
        android:src="@drawable/image2" />

    <View
        android:id="@+id/view_clickable_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#aa000000" />


</RelativeLayout>

我想在获取坐标后使 Imageview(myImage) 中的一小部分图像可点击。它对我来说很好用。 现在我想获得这张图片的缩放功能。当我放大时,可点击区域和图像也会相应地缩放。

我的问题是,我想在 ImageView 中获取图像的高度(不包括顶部和底部的黑色空间。由于 ImageView 设置为匹配父级,图像在横向模式下显示在屏幕中央)。每次我都得到 imageview 的高度。

我获取图像和 ImageView 高度的代码:

 int imagWidth = imageView.getWidth();
        int h = imageView.getHeight();


        int w = imageView.getDrawable().getIntrinsicWidth();
        int imagHeight = imageView.getDrawable().getIntrinsicHeight();

        Log.e("height", "Image height" + imagHeight + "\n" + "Imageview height" + h);

所以根据计算: 图像高度= 882 ImageView 高度 = 672

最佳答案

为我工作

    imgView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // Ensure you call it only once :
                imgView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                // Here you can get the size :)
                width = imgView.getWidth();
                height = imgView.getHeight();
            }
        });

关于android - 如何从 ImageView 获取实际图像宽度/高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49253225/

相关文章:

android - 如何在 ExoPlayer 中显示图像?

Android launchMode singleTask

android - 与 PC 相比,为什么 Android 中的响应时间(对于 Rest Call)较慢?

mdpi、hdpi、xhdpi、xxhdpi 的 Android 图像大小(仅限纵向)

android - 在主题中使用 fontFamily 属性时,Toast 使用 appcompat v26 引发 ArrayIndexOutOfBoundsException

android - 添加安卓功能

java - 错误 :(23, 26) 不允许字符串类型(位于 'src' ,值为 'pen' )。

Android 图像缩放为什么不使用 ScrollView

java - 在两个图像之间循环

android - 如何在更新gridview时避免闪烁?