如何在位图而不是屏幕上获取触摸事件上的坐标



>Greets ,

如何获取位图的坐标而不是屏幕的坐标。屏幕坐标由 event.getX(),event.getY() 方法获取,但不获取位图的坐标。请帮助任何人。

无法直接获取位图的坐标。你需要自己计算。使用图像视图的位置,您可以处理它。

当然,当您在活动创建之后时,您可以访问任何膨胀(活动)视图参数。举例说明。 图像视图 a; a.getPaddingBottom();像所有坐标一样(左右等)在此之后,您需要图像视图的高度和宽度。不,当您知道视图位置,hegiht和宽度时,您可以计算。

例:

final ImageView iv_YourImage = (ImageView) findViewById(R.id.iv_imageview);
public boolean onTouch(View v, MotionEvent event){
int topParam =  iv_YourImage.getPaddingTop();
 int rightParam =  iv_YourImage.getPaddingRight();
int maxTopParam = topParam+iv_YourImage.getMaxHeight();
int maxRightParam = rightParam + iv_YourImage.getMaxWidth();
 if(event.getX>topParam&&event.getX<maxTopParam){
    //the x coordinate is in your image... do the same to Y
 }
return true;
}
如果

答案太短,请查看以下代码:

Android:在ImageView中检测实际图像上的触摸

该代码替换了此答案的填充和最大高度编码,并使用getWidth()和getHeight()将其替换为显示图像的实际宽度和高度。并使用屏幕宽度和高度来计算其位置。如果你想更详细地回答你的问题,你应该提供更多信息,比如你在哪里画了位图......您是在活动 XML 中定义它,还是在随机位置(例如触摸事件的 X 和 Y 坐标)绘制它,答案取决于该信息。

package com.example.img;
imports....
public Image extends Activity {
ImageView imgYourImage;
// int imgWidth;
// etc...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image);
    imgYourImage = (ImageView) findViewById(R.id.yourImage);
    imgDimension();
}
private void imgDimension() {
    imgWidth = imgYourImage.getWidth();
    // at newer api's you can use getLeft() and getTop() of imageView
    // if getLeft() works you have the leftX coordinate of image already.
    // do same with height
    // also get the screen Width and Height by display.getWidth() (depreciated)
    // Or the newer code display.getSize()
    leftX = (screenwidth - imgWidth) / 2;
    rightx = leftx + imgWidth;
}

请注意,仅当图像显示在屏幕的水平中心时,此代码才有效。或者,如果图像显示在屏幕的垂直中心,则使用顶部和底部。

最新更新