2016-03-08 53 views
1

我想從我的視圖上的Asynctask繪製多個矩形。在我的MainActivity我稱之爲查看如下:從另一個類的畫布上繪製

public class MainActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     View bouncingBallView = new BouncingBallView2(this); 
     setContentView(bouncingBallView); 
     bouncingBallView.setBackgroundColor(Color.BLACK); 
    } 
} 

然後在我BouncingBallView我創作的畫布:

public class BouncingBallView2 extends View { 
    private Box box; 

    final BouncingBallView2 context = this; 
    private AsyncTask<Void, Void, Void> task; 


    // Constructor 
    public BouncingBallView2(Context context) { 
     super(context); 

     box = new Box(Color.BLACK); // ARGB 


     task=new PackagesPosition(); 
     task.execute(); 
    } 

    // Called back to draw the view. Also called after invalidate(). 
    @Override 
    protected void onDraw(Canvas canvas) { 
     // Draw the components 
     box.draw(canvas); 


     invalidate(); // Force a re-draw 
    } 

    // Called back when the view is first created or its size changes. 
    @Override 
    public void onSizeChanged(int w, int h, int oldW, int oldH) { 

     box.set(0, 0, w, h); 

    } 

正如你可以看到我所說的AsyncTask類,這也是BouncingBall內。 AsyncTask獲得每個框有四個值的框列表:x,y,width,height

Box類的工作原理如下:

public class Box { 
    int xMin, xMax, yMin, yMax; 
    private Paint paint; // paint style and color 
    private Rect bounds; 


    public Box(int color) { 
     paint = new Paint(); 
     paint.setColor(color); 
     bounds = new Rect(); 

    } 

    public void set(int x, int y, int width, int height) { 
     xMin = x; 
     xMax = x + width - 1; 
     yMin = y; 
     yMax = y + height - 1; 
     // The box's bounds do not change unless the view's size changes 
     bounds.set(xMin, yMin, xMax, yMax); 
    } 


    public void draw(Canvas canvas) { 
     canvas.drawRect(bounds, paint); 


    } 
} 

我不知道如何從AsyncTask添加一個框,因爲我沒有在畫布上直接訪問,你知道我應該如何進行? 任何幫助將非常感謝

+2

您可以在視圖類中擁有setter和getter,然後調用invalidate()來繪製內容。 – Raghunandan

+1

您可以通過AsyncTask的構造函數傳遞canvas的引用或使用接口獲取活動 – Ashiq

+0

@Raghunandan的位置,我該怎麼做?我有點失落,我剛開始使用Canvas – Alvaro

回答

0

我認爲最簡單的方法是通過Box類的構造函數注入畫布。但我個人不會在View之外油漆。我建議您在BouncingBallView2的內部移動您的繪畫並添加一個從AsyncTask調用的方法。該方法將控制動畫序列並在視圖上執行invalidate()