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
添加一個框,因爲我沒有在畫布上直接訪問,你知道我應該如何進行? 任何幫助將非常感謝
您可以在視圖類中擁有setter和getter,然後調用invalidate()來繪製內容。 – Raghunandan
您可以通過AsyncTask的構造函數傳遞canvas的引用或使用接口獲取活動 – Ashiq
@Raghunandan的位置,我該怎麼做?我有點失落,我剛開始使用Canvas – Alvaro