首页 > 解决方案 > 无法从相机返回的图像中获取正确的像素

问题描述

我正在尝试在图像视图中加载从设备相机返回的图像并获取我触摸的像素的颜色。

我尝试在 xml 文件中缩放图像,但是当我这样做时,虽然我看到图像适合 imageview,但触摸监听器以图像的原始尺寸工作。如果我不缩放它,我只会看到适合 imageview 的图像部分,而 touchlistener 会得到实际的像素。

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath)
        ivCamera.setImageBitmap(bitmap)
        ivCamera.setOnTouchListener { view, motionEvent ->
            val bmp = (ivCamera.drawable as BitmapDrawable).bitmap
            val pixel = bmp.getPixel(motionEvent!!.x.toInt(), motionEvent.y.toInt())
            pixelRed = Color.red(pixel)
            pixelGreen = Color.green(pixel)
            pixelBlue = Color.blue(pixel)
            tvColor.setBackgroundColor(Color.rgb(pixelRed!!, pixelGreen!!, pixelBlue!!))
            true
        }
    }
}


   <ImageView android:layout_width="match_parent"
           android:layout_weight="0.7"
           android:layout_height="0dp"
           android:id="@+id/ivCamera"
           android:scaleType="matrix"
           android:background="@android:drawable/ic_menu_report_image"
           app:layout_constraintEnd_toEndOf="parent"
           android:layout_marginEnd="8dp"
           android:layout_marginStart="8dp"
           app:layout_constraintHorizontal_bias="0.498"
           android:layout_margin="10dp"
           android:layout_marginBottom="8dp"
           android:adjustViewBounds="true"
           app:layout_constraintBottom_toBottomOf="parent"
           android:contentDescription="PicureTaken"/>

如果我在 xml 文件中缩放图像,我会在 imageview 中看到图像,但 touchlistener 在图像的原始尺寸下工作。如果我不缩放它,我只会看到适合 imageview 的图像部分,而 touchlistener 会得到实际的像素。

标签: androidkotlinandroid-imageviewdimensionsonactivityresult

解决方案


ivCamera.setOnTouchListener这可能是您在 XML 比例类型生效之前设置触摸侦听器的疯狂场景之一ivCamera.setImageBitmapscaleType即它在生效之前对原始尺寸进行了调整。

在 ImageView 完成充气后,您可以使用布局侦听器来设置触摸侦听器。

https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener

ivCamera.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            ivCamera.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            if(ivCamera.getDrawable() != null) {
                  ivCamera.setOnTouchListener {
                  // etc
                  // ...
            }

        }
    });

这不是我有信心的答案,而是一个答案。:-) 抱歉,这太可怕了/太糟糕了!


再看这个……

 val bmp = (ivCamera.drawable as BitmapDrawable).bitmap
 val pixel = bmp.getPixel(motionEvent!!.x.toInt(), motionEvent.y.toInt())

您从 ImageView 中获取位图,然后调用getPixel但显然.bitmap返回的是原始大小的位图,即使您使用scaleType.

我的建议是将触摸事件的 x/y 坐标转换为缩放的图像大小。

setImageBitmap或者在调用ImageView之前自己缩放位图。这样你就不需要翻译 x/y。


推荐阅读