我想在SurfaceView上对运动进行动画处理。理想情况下,动画结束后我也希望得到通知。

例如:
我可能有一辆向北的车。如果我想对其进行动画处理,以使其面向南方持续500毫秒,我该怎么做?

我正在使用SurfaceView,因此所有动画都必须手动处理,我认为我不能使用XML或android Animator类。

另外,我想知道在SurfaceView中连续进行动画处理的最佳方法(即步行周期)

最佳答案

手动旋转图像可能会有些麻烦,但是这就是我的操作方法。

private void animateRotation(int degrees, float durationOfAnimation){
    long startTime = SystemClock.elapsedRealtime();
    long currentTime;
    float elapsedRatio = 0;
    Bitmap bufferBitmap = carBitmap;

    Matrix matrix = new Matrix();

    while (elapsedRatio < 1){
        matrix.setRotate(elapsedRatio * degrees);
        carBitmap = Bitmap.createBitmap(bufferBitmap, 0, 0, width, height, matrix, true);
        //draw your canvas here using whatever method you've defined
        currentTime = SystemClock.elapsedRealtime();
        elapsedRatio = (currentTime - startTime) / durationOfAnimation;
    }

    // As elapsed ratio will never exactly equal 1, you have to manually draw the last frame
    matrix = new Matrix();
    matrix.setRotate(degrees);
    carBitmap = Bitmap.createBitmap(bufferBitmap, 0, 0, width, height, matrix, true);
    // draw the canvas again here as before
    // And you can now set whatever other notification or action you wanted to do at the end of your animation

}

这会将carBitmap旋转到在指定的时间+绘制最后一帧的时间中指定的任何角度。但是,有一个陷阱。这会旋转carBitmap,而不会正确调整其在屏幕上的位置。根据位图的绘制方式,最终使carBitmap旋转而位图的左上角保持原位。随着汽车的旋转,位图将拉伸(stretch)并调整以适应新的汽车尺寸,并用透明像素填充其周围的间隙。很难描述它的外观,因此下面是旋转正方形的示例:

灰色区域代表位图的完整大小,并用透明像素填充。要解决此问题,您需要使用三角函数。这有点复杂...如果最后对您来说是个问题(我不知道您是如何将位图绘制到 Canvas 上的,那么可能就不会这样),并且您无法解决该问题,请让我知道,我会贴出我的操作方法。

(我不知道这是否是最有效的方法,但是只要位图小于300x300左右,它对我来说就可以正常工作。也许有人知道更好的方法,他们可以告诉我们!)

关于android - 在“曲面 View ”中对图像进行动画处理和旋转,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2439301/

10-09 01:35
查看更多