将图像放在坐标Android上

时间:2010-06-11 06:26:52

标签: android image

我有一个程序,我想在触摸事件的坐标处放置一个图像。我现在有坐标我需要帮助才能在那里放置图像。我将使用drawable。

编辑** 我也想把它叠加在另一张图片上。我找不到任何关于此的文件。我认为应该很容易。

任何人都可以帮助我吗?

EDIT **** 知道了,现在我只需弄清楚如何在触摸点而不是左上角找到图像的中间位置:

 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;
        }
    });

3 个答案:

答案 0 :(得分:4)

将您想要的图像放在应用程序的xml中。 设置它隐形或消失...

取代:

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

在类构造函数之前:

ImageView touchView2;

和构造函数(onCreate)方法

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

现在通过在屏幕上进行所有触摸来设置onTouchEventListener。 如果这些坐标位于您喜欢的位置,则使用按下的X和Y坐标调用placeImage方法。这个方法放在类构造函数(onCreate)之外,所以下面的第一个方法应该是正确的:

@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;
}

现在是placeImage方法:

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);
}

这应该是你的答案......现在你只需要使touchView可见:

touchView2.setVisibility(0);

答案 1 :(得分:0)

Drawable recycle_bin = context.getResources().getDrawable(android.R.drawable.ic_menu_delete);
int w = recycle_bin.getIntrinsicWidth();
int h = recycle_bin.getIntrinsicHeight();
int x = getWidth()/2 - w/2;
int y = getHeight() - h - 5;

recycle_bin.setBounds( x, y, x + w, y + h );
recycle_bin.draw( canvas );

这就是我在底部中心绘制回收站图标的方式

答案 2 :(得分:0)

要将图像放置在某个坐标处,您必须在画布上绘制图像。要获取触摸事件的坐标,请使用以下代码:

@Override
public void onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        mTouchX = event.getX();
        mTouchY = event.getY();//stores touch event
    } else {
        mTouchX = -1;
        mTouchY = -1;
    }
    super.onTouchEvent(event);
}
相关问题