Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place image at coordinates Android

Tags:

android

image

I have a program in which I would like to place an image at the coordinates of a touch event. I have the coordinates now I just need help with placing an image there. I will be using a drawable.

Edit** I also want to overlay it over another image. I cant find any documentation on this what so ever. I would think it should be easy.

Can anyone help me?

EDIT**** Got it, now I just have to figure out how to get the middle of the image at the touch spot and not the top left corner:

 final View touchView2 = findViewById(R.id.ImageView02);
    touchView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.v("x,y",event.getY()+","+event.getX());
            touchView2.bringToFront();
            int y = (int)event.getY();
            int x = (int)event.getX();

            touchView2.layout(x, y, x+48, y+48);
                return true;
        }
    });
like image 267
shaneburgess Avatar asked Jun 11 '10 06:06

shaneburgess


1 Answers

place the image you want on top in the xml of your application. set it invisible or gone...

replace:

 final View touchView2 = findViewById(R.id.ImageView02);

before the classes constructor:

ImageView touchView2;

and in the constructor (onCreate) method

touchView2 = (ImageView) findViewById(R.id.ImageView02);

Now set up a onTouchEventListener by getting all touches on the screen. If those coordinates are in a position you like call the placeImage method with the pressed X and Y coordinate. this method is placed outside the class constructor (onCreate) so first method below should be right:

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);
    int eventAction = event.getAction();
    switch(eventAction) {
        case MotionEvent.ACTION_DOWN:
            float TouchX = event.getX();
            float TouchY = event.getY();
            placeImage(TouchX, TouchY);
            break;
    }        
    return true;
}

now the placeImage method:

private void placeImage(float X, float Y) {
    int touchX = (int) X;
    int touchY = (int) Y;

    // placing at bottom right of touch
    touchView2.layout(touchX, touchY, touchX+48, touchY+48);

    //placing at center of touch
    int viewWidth = touchView2.getWidth();
    int viewHeight = touchView2.getHeight();
    viewWidth = viewWidth / 2;
    viewHeight = viewHeight / 2;

    touchView2.layout(touchX - viewWidth, touchY - viewHeight, touchX + viewWidth, touchY + viewHeight);
}

This should be your answer... now you only have to make touchView visible:

touchView2.setVisibility(0);
like image 174
Frank Jacobs Avatar answered Sep 25 '22 20:09

Frank Jacobs