android - 无法从相机返回的图像中获取正确的像素
问题描述
我正在尝试在图像视图中加载从设备相机返回的图像并获取我触摸的像素的颜色。
我尝试在 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 会得到实际的像素。
解决方案
ivCamera.setOnTouchListener
这可能是您在 XML 比例类型生效之前设置触摸侦听器的疯狂场景之一ivCamera.setImageBitmap
。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
返回的是原始大小的位图,即使您使用scaleType
.
我的建议是将触摸事件的 x/y 坐标转换为缩放的图像大小。
setImageBitmap
或者在调用ImageView之前自己缩放位图。这样你就不需要翻译 x/y。
推荐阅读
- node.js - 为什么我无法从 nodejs 向我的 mongodb 数据库发出任何请求
- javascript - 如何使用 Css display:none 和 javascript className 删除输入字段
- mysql - 获取错误代码:1055。来自 MySQL 查询,即使我使用 ANY_VALUE()
- javascript - 如何在使用 Web Animations API 完成之前暂停动画?
- python - Python 自动格式化增加了额外的空格
- javascript - 即使它正在工作,也无法读取未定义的属性“导航”
- node.js - 没有通过 Sequelize 实例
- puppeteer - puppeteer headless:虚假超时,真实作品
- teensy - MPU 6050 加速度计发送 16 位无符号值
- r - 如何用不同的水平线注释 ggplot2 中的每个条?