Hi我想在触摸图像视图时获得像素颜色,当xml中图像视图的宽度和高度是包装内容时,此代码工作良好
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".2"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/iv_cam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" >
</ImageView>
</LinearLayout>
,当在xml文件中我设置图像视图包装内容的宽度和高度以匹配父时,问题出现了
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".2"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/iv_cam"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_launcher" >
</ImageView>
</LinearLayout>
通过这样做,小图像变得有张力错误来了E/MessageQueue JNI(1006):java.lang.IollegalArgumentException:x必须<bitmap.width()
我该怎么解决这个问题。。。
@Overridepublic boolean onTouch(View v,MotionEvent事件){
if(event.getAction() == MotionEvent.ACTION_DOWN){
ImageView iv = ((ImageView)v);
Bitmap bmp = ((BitmapDrawable)iv.getDrawable()).getBitmap();
int pixel = bmp.getPixel((int)event.getX(),(int)event.getY());// error comes in this line
int alphaValue = Color.alpha(pixel);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
Toast.makeText(this,"[" +alphaValue+"," +redValue+","+greenValue+","+blueValue+"]", Toast.LENGTH_LONG).show();
}
return false;
}
您需要对照位图本身检查位图的尺寸。
if ((bmp.getHeight() < (int)event.getY() || (bmp.getWidth() < (int)event.getX() ) {
// not within range
}
我知道这是一个老问题,但它可能仍然相关。据我所知,位图引用的像素与使用事件的getPixel()获得的像素不同。我所做的是将这些像素偏移如下:
Bitmap bmp = Bitmap.createBitmap(img.getDrawingCache());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int [] imgCenter = new int[2];
img.getLocationOnScreen(imgCenter);
int x = evX - imgCenter[0]; // These are your desired coordinates
int y = evY - imgCenter[1]; // evX & evY are the event's coordinates