用户触摸的新图像

时间:2015-12-14 18:16:14

标签: android ontouchevent motionevent

嗨,我是android的新手。我的问题是有没有任何功能可以显示从drawable到屏幕的图像。顺便说一句,我可以在我触摸的坐标上移动相同的图像,我只需要将新图像放在我触摸的坐标上。

这是我的代码:

public class MainActivity extends Activity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

    private void placeImage(float X, float Y) {
        ImageView flower = (ImageView) findViewById(R.id.img);

        int touchX = (int) X;
        int touchY = (int) Y;


        flower.layout(touchX, touchY, touchX + 48, touchY + 48);


        int viewWidth = flower.getWidth();
        int viewHeight = flower.getHeight();
        viewWidth = viewWidth / 2;
        viewHeight = viewHeight / 2;

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



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

1 个答案:

答案 0 :(得分:0)

假设您将图片放在FrameLayout内:

private void placeImage(float X, float Y) {
    ImageView flower = (ImageView) findViewById(R.id.img);

    int touchX = (int) X;
    int touchY = (int) Y;

    FrameLayout.LayoutParams mlp = (FrameLayout.LayoutParams) flower.getLayoutParams();
    mlp.marginLeft = touchX;
    mlp.marginTop = touchY;
    mlp.width = FrameLayout.LayoutParams.WRAP_CONTENT;
    mlp.height = FrameLayout.LayoutParams.WRAP_CONTENT;
    flower.setLayoutParams(mlp);
}

此外,可以在设计时将宽度和高度设置为WRAP_CONTENT ,以告诉元素将其大小设置为内容大小。

<小时/> 可以通过创建新的ImageView来添加新图像。

protected void onCreate(Bundle savedInstanceState){
    ...
    frameLayout = (FrameLayout) findViewById(R.id.box);
    ...
}

private void placeImage(float X, float Y) {
    ImageView newImage = new ImageView(this);
    //Set contents of new ImageView
    newImage.setImage(R.drawable.example_image);
    //Create layout parameters object with width and height set to size of contents
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
    //Offset image by X and Y from left and top of its parent, in our case FrameLayout
    lp.marginLeft = X;
    lp.marginTop = Y;
    //Add new ImageView into layout
    frameLayout.AddView(newImage, lp);
}

frameLayout引用您放置在布局中的FrameLayout视图组,而R.drawable.example_image是您要显示的图片。