简体   繁体   中英

OnTouchListener coordinates being incorrect

I have an OnTouchListener however when I actually test my program and touch the screen is displays a colour that is not what it should be. I tested using blocks of colours and it works however the coordinates are still off and if you touch too far on one colour it will show you a different one. I believe this is because the the coordinates produced are in comparison to the whole screen instead of the image view - where i want it to be selected from. How would i make the OnTouchListener be for just the image view and not the whole screen? Thank you.

final Bitmap bitmap2 = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    imageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {


            Matrix inverse = new Matrix();
            v.getMatrix().invert(inverse);
            float[] touchPoint = new float[] {event.getX(), event.getY()};
            inverse.mapPoints(touchPoint);
            int x = Integer.valueOf((int)touchPoint[0]);
            int y = Integer.valueOf((int)touchPoint[1]);


          //  int x = (int) event.getX();
           // int y = (int) event.getY();
            int pixel = bitmap2.getPixel(x, y);


            int red = Color.red(pixel);
            int blue = Color.blue(pixel);
            int green = Color.green(pixel);

            Bitmap bitmap = BitmapFactory.decodeFile(output.getAbsolutePath());
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.rgb(red,green,blue));


            Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
            Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);


            Canvas canvas = new Canvas(mutableBitmap);
            canvas.drawRect(50, 50, 500, 250, paint);

            ImageView imageView = (ImageView)findViewById(R.id.Image_view);
            imageView.setAdjustViewBounds(true);
            imageView.setImageBitmap(mutableBitmap);


            return true;
            }

    });

}


}

I believe this is because the the coordinates produced are in comparison to the whole screen

Yes, you need to do some simple deduction to get the touch coordinates on the imageView:

int[] imgCoords = new int[2];
imageView.getLocationOnScreen(imgCoords);

get the X,Y of the touch and take away the imageView coordinates from it:

int wholeX = (int) event.getX();
int wholeY = (int) event.getY();

int imageX = wholeX - imgCoords[0];
int imageY = wholeY - imgCoords[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM