我的应用程序在Canvas周围启动精灵实例,然后这些实例沿着屏幕向x/y坐标移动。我希望能够围绕其中心旋转精灵,使其面对目标坐标。我正在使用精灵表,并且遇到了剪裁问题。我也找到了很多好的例子,但似乎没有完全涵盖我所需要的。这个例子非常接近,但为了效率,我使用了一个ImagePooler类,不能在每次绘制/旋转时重新加载图像。因此,如果有人有关于如何旋转预加载图像而不切割我的精灵表的想法,我将非常感激。
首先,旋转精灵非常容易,可以使用画布或矩阵:
Matrix matrix = new Matrix();
matrix.postRotate(angle, (ballW / 2), (ballH / 2)); //rotate it
matrix.postTranslate(X, Y); //move it into x, y position
canvas.drawBitmap(ball, matrix, null); //draw the ball with the applied matrix
// method two
canvas.save(); //save the position of the canvas
canvas.rotate(angle, X + (ballW / 2), Y + (ballH / 2)); //rotate the canvas' matrix
canvas.drawBitmap(ball, X, Y, null); //draw the ball on the "rotated" canvas
canvas.restore(); //rotate the canvas' matrix back
//in the second method only the ball was roteded not the entire canvas
要将其转向目标,您需要知道精灵和目标之间的角度:
spriteToDestAngle = Math.toDegrees(Math.atan2((spriteX - destX)/(spriteY - destY)));
现在你需要做的就是使用该角度来旋转精灵,再加上一个常量angleShift来调整它,该常量取决于精灵最初所指向的方向。
我不确定这是否有效,但希望能给你一些想法...
使用this参考来计算角度:
private double angleFromCoordinate(double lat1, double long1, double lat2,
double long2) {
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
brng = 360 - brng;
return brng;
}
然后将ImageView旋转到这个角度
private void rotateImage(ImageView imageView, double angle) {
Matrix matrix = new Matrix();
imageView.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angle, imageView.getDrawable().getBounds()
.width() / 2, imageView.getDrawable().getBounds().height() / 2);
imageView.setImageMatrix(matrix);
}