Android 2.2 Щелкните и перетащите изображение по центру касания

Я пытаюсь перетащить перекрестие на MapView . У меня есть кнопка ImageView на экране. Когда я касаюсь ее, кнопка исчезает и появляется новый ImageView .Новый ImageView должен находиться по центру под моим пальцем, пока я где-нибудь его не отпущу, но по какой-то причине смещение неверно. Прицел появляется внизу справа от того места, где я касаюсь.

Изображение перемещается пропорционально, поэтому я считаю, что проблема связана с параметрами offset_x и offset_y , которые я определяю в разделе ACTION_DOWN . Затем в ACTION_UP мне нужно createMarker (x, y) с правильными координатами под моим пальцем, но он также смещен неправильно.

Я пробовал разные способы сделать это по центру, и некоторые из них лучше, чем другие. Мне до сих пор не удавалось заставить его работать без использования магических чисел.

Как бы то ни было, я использую место щелчка и вычитаю половину размера изображения. Для меня это имеет смысл. Это будет ближе к правильному, если я вычту весь размер изображения. Я пробовал различные примеры из Интернета, все они страдают неточностями с местоположением View .

Вы можете мне дать совет?

crosshair = (ImageView)findViewById(R.id.crosshair);
frameLayout = (FrameLayout)findViewById(R.id.mapframe);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
crosshairImage = BitmapFactory.decodeResource(getResources(), R.drawable.crosshair);
crosshair.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            dragStatus = START_DRAGGING;

            // hide the button and grab a mobile crosshair
            v.setVisibility(View.INVISIBLE);
            image = new ImageView(getBaseContext());
            image.setImageBitmap(crosshairImage);

            // set the image offsets to center the crosshair under my touch
            offset_x = (int)event.getRawX() - (int)(crosshairImage.getWidth()/2)  ;
            offset_y = (int)event.getRawY() - (int)(crosshairImage.getHeight()/2) ;

            // set the image location on the screen using padding
            image.setPadding(offset_x, offset_y, 0, 0);

            // add it to the screen so it shows up
            frameLayout.addView(image, params);
            frameLayout.invalidate();

            if(LOG_V) Log.v(TAG, "Pressed Crosshair");
            return true;
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            if(dragStatus == START_DRAGGING) {
                dragStatus = STOP_DRAGGING;

                // place a marker on this spot
                makeMarker((int)event.getX() + offset_x, (int)event.getY() + offset_y); 

                // make the button visible again
                v.setVisibility(View.VISIBLE);

                // remove the mobile crosshair
                frameLayout.removeView(image);

                if(LOG_V) Log.v(TAG, "Dropped Crosshair");
                return true;
            }
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (dragStatus == START_DRAGGING) {
                // compute how far it has moved from 'start' offset
                int x =  (int)event.getX() + offset_x;
                int y = (int)event.getY() + offset_y; 

                // check that it's in bounds
                int w = getWindowManager().getDefaultDisplay().getWidth();
                int h = getWindowManager().getDefaultDisplay().getHeight();
                if(x > w)
                    x = w;
                if(y > h)
                    y = h;

                // set the padding to change the image loc
                image.setPadding(x, y, 0 , 0);

                // draw it
                image.invalidate();
                frameLayout.requestLayout();

                if(LOG_V) Log.v(TAG, "(" + offset_x + ", " + offset_y + ")");

                return true;
            }
        }               
        return false;
    }

});
9
задан Barney 3 March 2013 в 14:40
поделиться