如果您需要使用一个处理程序图标同时调整图像大小和旋转图像,则应执行一些三角计算。
根据图像的初始角度和连接图像中心与当前手指位置的矢量旋转的角度,计算图像应旋转的角度并不困难。稍微复杂一点的任务是将处理程序放置在屏幕的适当位置,使其始终连接主图像的一角。
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
--这计算主图像对角线的一半长度,i。 e.其中心与角点之间的距离
Math.atan2(imageView.getHeight(), imageView.getWidth())
--这是对角线最初旋转的角度(因为图像不能是正方形,所以这个角度并不总是 45 度)
Math.cos(Math.toRadians(newRotation) + Math.atan2(imageView.getHeight(), imageView.getWidth()))
--这为我们提供了单位向量 X 轴上的投影,旋转了一个由图像旋转角度及其对角线初始旋转角度组成的角度。乘以对角线长度的一半后,我们得到图像角点的X。
与 Y 相同,但使用sin
代替cos
.