1.当view 在进行setScale操作缩小后,view.getWidth 和view.getHeight 并不会有变化,原本是多少像素的,大小还是多少像素。
而当处理触摸事件时,需要通过MotionEvent.x,MotionEvent.y 来判断 触摸点是否在缩小后的view(红色框部分)的显示范围时,假如通过getleft/getRight/getTop/getBottom来判断的话:
return x >= view.getLeft() &&
x < view.getRight() &&
y >= view.getTop() &&
y < view.getBottom();
会将缩小后产生的空白部分(蓝色下划线)也判断为true ,如下图:
所以当对View进行setTranslation或setScale等变换时,可以通过getTranslation和getScale,然后对getL/T/R/B 的值进行计算来获取变换后的View的显示区域,但这样太麻烦,有种更简单的方法。
2.getLocationOnScreen可以获取View在屏幕中的绝对坐标,而这个值会根据setScale而改变。
比如要判断触摸点是否在scale后的view内时,可以通过如下代码判断:
int[] viewLocation = new int[2];
view.getLocationOnScreen(viewLocation);
int[] parentLocation = new int[2];
parentView.getLocationOnScreen(parentLocation);
int screenX = parentLocation[0] + x;
int screenY = parentLocation[1] + y;
return screenX >= viewLocation[0] && //Left
screenX < viewLocation[0] + (int)(view.getWidth() * view.getScaleX()) && //Right
screenY >= viewLocation[1] && //Top
screenY < viewLocation[1] + (int)(view.getHeight() * view.getScalelY());//Bottom
通过计算parentview(就是Layout)的LocationOnScreen,加上MotionEvent.x,MotionEvent.y就可以得出触摸点在屏幕中的位置,然后通过与view的LocationOnScreen比对就可以。