2011-05-30 63 views
0

我有以下類:動畫效果的onDraw()段

public class MainActivity extends Activity { 
/** Called when the activity is first created. */ 

String value = "0"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 

     setContentView(new GaugeAnimation(this)); 

     } 

    } 

我GuageAnimation類如下:

public class GaugeAnimation extends View{ 

private Path p; 
private Paint cPaint = new Paint(); 
private int width = 200; 
private int angleStart = 135; 
private int sweep = 90; 
private int value=0; 

Bitmap bottom = BitmapFactory.decodeResource(getResources(), R.drawable.dashboard_rpm_bottom); 
Bitmap top= BitmapFactory.decodeResource(getResources(), R.drawable.dashboard_rpm_active); 

public GaugeAnimation(Context context){ 
    super (context); 

     //Arc Equations & etc.... 

} 

@Override 
public void onDraw(Canvas c){ 


    Paint paint = new Paint(); 
    paint.setFilterBitmap(false); 
    paint.setColor(Color.BLUE); 
    c.translate(55,320);  

    //Draw bottom image on canvas 

    c.save(); 

    p.addArc(new RectF(0,0,width,width), angleStart, sweep); 
    p.lineTo(width/2, width/2); 


    c.clipPath(p); 

    //draw Image on top 

    c.restore(); 

    invalidate() 

} 


} 

所以基本上這個作物在一個時間的圓形圖像一塊基於弧方程。我想顯示一個動畫,如圈子的所有部分都被填充(所以顯示每個被修剪的路徑,以顯示正在構建的圓形)。所以我想做得像循環:

for (int i=0; i<100; i++) { 
    sweep=i; 
    p.addArc(new RectF(0,0,width,width), angleStart, sweep); 
    p.lineTo(width/2, width/2); 

    c.clipPath(p); 
     invalidate(); 
} 

但是,這並不工作,它只是繪製最終結果當i = 100,人有一個想法,我怎麼能做到這一點?

回答

1

當前您的循環在主線程中執行並保持繁忙,所以在完成之前它不會實際更新UI。

您應該在後臺線程中使用循環(使用TimerAsyncTask)並在主線程上執行繪製。請注意,如果不進行短暫的睡眠,它可能會看起來像動畫太多,速度會非常快。