我正在尝试从我的视图中的Asynctask中绘制多个矩形。在我的MainActivity中,我将View调用如下:
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
。
框类的工作原理如下:
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
添加一个框,因为我无法直接访问Canvas,你知道我该怎么办?
任何帮助都会非常感激
答案 0 :(得分:0)
我认为最简单的方法是通过Box
类的构造函数注入画布。我个人不会在View
之外画画。我建议您在BouncingBallView2
内移动您的绘画,并添加一个从AsyncTask
调用的方法。此方法将控制动画序列并在视图上执行invalidate()
。