在Android中将图片放置在指定坐标处

7
我有一个程序,想在一个触摸事件的坐标上放置一张图像。我已经有了这些坐标,现在只需要帮助将图像放在那里。我将使用可绘制对象。
编辑** 我还想在另一张图像上覆盖它。我找不到任何关于此的文档。我认为这应该很容易。
有人能帮我吗?
编辑**** 明白了,现在我只需弄清楚如何将图像中心放在触摸点而不是左上角:
 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个回答

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

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

我有点击的坐标,如何在点击位置放置图像?由于我的应用程序支持API-10,因此无法使用setX()和setY()。 - Rana Ranvijay Singh

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

这就是我如何在底部中心绘制回收站图标


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接