gpt4 book ai didi

android - 无法从相机返回的图像中获取正确的像素

转载 作者:行者123 更新时间:2023-11-29 02:19:54 24 4
gpt4 key购买 nike

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

我尝试缩放 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 会获得实际像素。

最佳答案

这可能是您在 XML 缩放类型 ivCamera.setImageBitmap 生效之前设置触摸监听器 ivCamera.setOnTouchListener 的疯狂场景之一。也就是说,它在 scaleType 生效之前设置了对原始尺寸的触摸。

您可以使用布局监听器在 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 返回给您原始大小的位图,即使您缩放了它(对于 View ) 与 scaleType

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

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

关于android - 无法从相机返回的图像中获取正确的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com