如果需要使用一个处理程序图标同时调整大小和旋转图像,则应执行一些三角计算。
基于图像的初始角度和连接图像中心和当前手指位置的矢量旋转的角度,计算图像旋转的角度并不是很困难。稍微复杂一点的任务是将处理程序放置在屏幕的适当位置,以使其始终连接到主图像的角落。
public void setUpResize() { dragHandle.setonTouchListener(new View.onTouchListener() { float centerX, centerY, startR, startScale, startX, startY, startRotation, startA ; public boolean onTouch(View v, MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN) { centerX = (imageView.getLeft() + imageView.getRight()) / 2f; centerY = (imageView.getTop() + imageView.getBottom()) / 2f; startX = e.getRawX() - dragHandle.getX() + centerX; startY = e.getRawY() - dragHandle.getY() + centerY; startR = (float) Math.hypot(e.getRawX() - startX, e.getRawY() - startY); startA = (float) Math.toDegrees(Math.atan2(e.getRawY() - startY, e.getRawX() - startX)); startScale = imageView.getScaleX(); startRotation = imageView.getRotation(); } else if (e.getAction() == MotionEvent.ACTION_MOVE) { float newR = (float) Math.hypot(e.getRawX() - startX, e.getRawY() - startY); float newA = (float) Math.toDegrees(Math.atan2(e.getRawY() - startY, e.getRawX() - startX)); float newScale = newR / startR * startScale; float newRotation = newA - startA + startRotation; imageView.setScaleX(newScale); imageView.setScaleY(newScale); imageView.setRotation(newRotation); // ----- this part takes some effort to understand... ------ dragHandle.setX((float) (centerX + Math.hypot(imageView.getWidth(), imageView.getHeight())/2f * newScale * Math.cos(Math.toRadians(newRotation) + Math.atan2(imageView.getHeight(), imageView.getWidth())))); dragHandle.setY((float) (centerY + Math.hypot(imageView.getWidth(), imageView.getHeight())/2f * newScale * Math.sin(Math.toRadians(newRotation) + Math.atan2(imageView.getHeight(), imageView.getWidth())))); //----------------------------------------------------------- dragHandle.setPivotX(0); dragHandle.setPivotY(0); dragHandle.setRotation(newRotation); } else if (e.getAction() == MotionEvent.ACTION_UP) { } return true; } });}所以,我在做什么?
Math.hypot(imageView.getWidth(), imageView.getHeight()) / 2f * newScale
-这将计算主图像对角线的一半长度,即其中心和角点之间的距离
Math.atan2(imageView.getHeight(), imageView.getWidth())
-这是对角线最初旋转的角度(由于图像不能为正方形,因此该角度并不总是45度)。
Math.cos(Math.toRadians(newRotation) + Math.atan2(imageView.getHeight(), imageView.getWidth()))
-这使我们可以投影到单位矢量的X轴上,并旋转一个角度,该角度由旋转图像的角度及其对角线的初始旋转角度组成。将其乘以对角线的一半长度后,我们得到图像角的X。
与Y相同,但使用
sin代替
cos。



