2011-05-14 69 views
5

我的應用程序在Canvas周圍啓動精靈實例,然後在屏幕上向x/y座標移動。我希望能夠圍繞其中心旋轉精靈,使其面向目標座標。我正在使用精靈表,並且遇到剪輯問題。我也找到了很多很好的例子,但是沒有任何東西可以覆蓋我正在尋找的東西。 This example is very close但爲了提高效率,我正在使用ImagePooler類,無法在每次繪製/旋轉時重新加載圖像。所以,如果有人想知道如何旋轉預加載的圖像來切割我的精靈表,我將非常感激。Android:如何根據目標的座標旋轉移動的動畫精靈

回答

13

首先,它很容易旋轉,你可以用帆布或矩陣精靈:

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一樣的常量,這取決於你的精靈初始點的位置。

我不知道這是否會工作,但希望它可以給你一些想法...

+0

我的精靈每個人都有自己的繪畫方法,我用一個矩形對象拉出精靈表我想畫的一部分,所以矩陣的選擇似乎是出questio的ñ(雖然由於某種原因,我認爲這是我更喜歡的選擇)。但是,Canvas方法正在(幾乎)正如我所希望的那樣工作,並對你的spriteToDestAngle代碼進行了一些調整,我將找到所需的東西。 – bwags 2011-05-14 23:56:13

+0

很高興有用:) – Lumis 2011-05-16 10:00:38

0

使用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); 
}