微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ImageView - 获取触摸像素的颜色

如何解决ImageView - 获取触摸像素的颜色

我有以下图片,由三种颜色(白色、灰色、黑色)组成:

enter image description here

 <ImageView
        android:id="@+id/iv_colors"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:scaleType="fitStart"
        android:adjustViewBounds="true"
        android:src="@drawable/colors"
        />

触摸时,我想知道这些区域中的哪些区域被点击了 - 白色、灰色或黑色。我试过this approach

final Bitmap bitmap = ((BitmapDrawable) ivColors.getDrawable()).getBitmap();
ivColors.setonTouchListener((v,event) -> {
        int x = (int) event.getX();
        int y = (int) event.getY();
        int pixel = bitmap.getPixel(x,y);
        int redValue = Color.red(pixel);
        int blueValue = Color.blue(pixel);
        int greenValue = Color.green(pixel); 
        return false;
    });
}

然而,每次都会出现以下异常:

java.lang.IllegalArgumentException: x must be < bitmap.width()

正如几乎所有地方所述,这是我的问题类型的解决方案。但是,它在我的项目中不起作用。有人可以帮我解决这个问题吗?

解决方法

它不起作用,因为位图的大小与 ImageView 的大小不同

试试这个,

imageView.setOnTouchListener((v,event) -> {

    int viewX = (int) event.getX();
    int viewY = (int) event.getY();

    int viewWidth = imageView.getWidth();
    int viewHeight = imageView.getHeight();

    Bitmap image = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    int imageX = (int)((float)viewX * ((float)imageWidth / (float)viewWidth));
    int imageY = (int)((float)viewY * ((float)imageHeight / (float)viewHeight));

    int currPixel = image.getPixel(imageX,imageY);

    Log.d("Coordinates","(" + String.valueOf(Color.red(currPixel)) + "," + String.valueOf(Color.blue(currPixel)) + "," + String.valueOf(Color.green(currPixel)) + ") Pixel is: " + currPixel);

    return false;
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。