2013-05-10 87 views
2

我想在我的活動中有一個動畫圖像: 只是一個在軌跡(黑線)上移動的白色圓圈。Android圖像動畫 - 在軌跡上移動

enter image description here

什麼是做到這一點的最好方法是什麼?

  1. 翻譯動畫
  2. FrameAnimation
  3. 帆布

實現可能是:

  1. 的白色圓圈是一個小的ImageView與透明背景。它放在另一個ImageView(黑色曲線)的頂部。
  2. FrameAnimation:對於圓的每個位置,都有一個單獨的整個屏幕的png圖像,它是動畫的一個框架。
  3. 使用drawCircle()和restoreBackgroundImage()爲白點的每個移動。

到目前爲止我嘗試了一個FrameAnimation,但是我得到了10幀的outOfMemoryError。

+0

嘗試https://github.com/JakeWharton/NineOldAndroids – DjHacktorReborn 2013-05-10 11:43:40

回答

0

以下代碼實現了Canvas的方式。高效且無OOM。你只需要將你的軌跡變成一個Path對象。

public class TestView extends View { 
    private Path path; 
    private Paint pathPaint; 
    private Paint dotPaint; 
    private long beginTime; 
    private long duration = 3000; 
    private float dotRadius = 3; 
    private PathMeasure pm; 

    public TestView(Context context) { 
     super(context); 
     init(); 
    } 

    public TestView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(); 
    } 

    private void init() { 
     path = new Path(); 
     path.moveTo(0, 100); 
     path.lineTo(100, 200); 
     path.lineTo(200, 50); 
     //TODO: Put your path here 

     pm = new PathMeasure(path, false); 
     pathPaint = new Paint(); 
     pathPaint.setARGB(255, 0, 0, 0); 
     pathPaint.setStrokeWidth(2); 
     pathPaint.setStyle(Paint.Style.STROKE); 
     dotPaint = new Paint(); 
     dotPaint.setARGB(255, 255, 255, 255); 
     dotPaint.setStyle(Paint.Style.FILL); 
     beginTime = 0; 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     canvas.drawARGB(0, 0, 0, 0); 
     canvas.drawPath(path, pathPaint); 

     long currentTime = System.currentTimeMillis(); 
     float currentDistance; 

     if (beginTime == 0) { 
      beginTime = currentTime; 
      currentDistance = 0; 
     } else if (beginTime > 0 && currentTime - beginTime < duration) { 
      currentDistance = (float) (currentTime - beginTime)/(float) duration * pm.getLength(); 
     } else { 
      beginTime = -1; 
      return; 
     } 

     float pos[] = new float[2]; 
     pm.getPosTan(currentDistance, pos, null); 
     canvas.drawCircle(pos[0], pos[1], dotRadius, dotPaint); 
     invalidate(); 
    } 
}