imageView.setOnTouchListener(imgSourceOnTouchListener); OnTouchListener imgSourceOnTouchListener = new OnTouchListener(){ @Override public boolean onTouch(View view, MotionEvent event) { float eventX = event.getX(); float eventY = event.getY(); float[] eventXY = new float[] {eventX, eventY}; Matrix invertMatrix = new Matrix(); ((ImageView)view).getImageMatrix().invert(invertMatrix); invertMatrix.mapPoints(eventXY); int x = Integer.valueOf((int)eventXY[0]); int y = Integer.valueOf((int)eventXY[1]); Drawable imgDrawable = ((ImageView)view).getDrawable(); Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap(); //Limit x, y range within bitmap if(x < 0){ x = 0; }else if(x > bitmap.getWidth()-1){ x = bitmap.getWidth()-1; } if(y < 0){ y = 0; }else if(y > bitmap.getHeight()-1){ y = bitmap.getHeight()-1; } int touchedRGB = bitmap.getPixel(x, y); System.out.println("touched color: " + "#" + Integer.toHexString(touchedRGB)); return true; }};
比較需要注意的是這一行
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap(); 如果你的ImageView的圖是設成background,你這一行要改寫成
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBackground();
沒有留言:
張貼留言