android:根据用户触摸的位置在显示器上放置图像(api 11+)



你好,我正试图在用户触摸的区域上放置一个imageview。

使用MotionEvent event简单地做imageview.setX(event.getX())imageview.setY(event.getY())并不是完全的解决方案。

我意识到这些是像素值,所以我尝试使用(int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, event.getX() , getResources() .getDisplayMetrics()); 将事件值转换为与密度无关的值

但当我试图在这个位置显示图像视图时,这仍然不能给我提供与我触摸的位置匹配的坐标。

此外,当我希望坐标位于图像视图的中心时,我怀疑图像视图会在这些坐标处绘制其左上角。

Insight赞赏

您很可能想要执行以下操作:

如果您试图找到缩放图像的触摸事件点上的点:

public static float[] getPointerCoords(ImageView view, MotionEvent e)
{
    final int index = e.getActionIndex();
    final float[] coords = new float[] { e.getX(index), e.getY(index) };
    Matrix matrix = new Matrix();
    view.getImageMatrix().invert(matrix);
    matrix.postTranslate(view.getScrollX(), view.getScrollY());
    matrix.mapPoints(coords);
    return coords;
}
public boolean onTouch(View v, MotionEvent event)
{
    float[]     returnedXY  = getPointerCoords((ImageView) v, event);
    imageView.setLeft(returnedXY[0] + (imageView.getWidth() /2));
    imageView.setTop(returnedXY[1] + (imageView.getHeight() /2));
}

如果没有,只需使用events.getX和getY。您可能需要使用事件的getRawX和getRawY。

最新更新