android:如何在另一个自定义类的画布上绘制?

时间:2016-08-31 20:42:31

标签: android canvas view

如果有人可以提供帮助,我将非常感激。

我在xml文件中创建了一个带有TableLayout的视图网格。 在相应的java文件中,我检索数组视图中所有视图的id。 我有另一个类在其构造函数中接收对上面创建的视图的引用,以便在其画布上绘制。

public class Mosaique extends Activity {

Box [][]box = new Box[NL][NC];

View [][] boxMosaique = new View[NL][NC];
//...
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.mosaique);

    boxMosaique[0][0] = findViewById(R.id.b_00);
    boxMosaique[0][1] = findViewById(R.id.b_01);
    boxMosaique[0][2] = findViewById(R.id.b_02);
//…
for (int lig=0;lig<NL;lig++)
        for(int col=0;col<NC;col++)
          box[lig][col] = new Box(boxMosaique[lig][col], bckgrnd_color, lig,col);
}
//...
}
// The constructor of the another class which access the views for drawing

public Box(View aView, int backGroundColor, int lig, int col){

    this.aView = aView;
    this.lig = lig;
    this.col = col;
    this.backGroundColor = backGroundColor;
// How to access the canvas of aView for drawing  ?
}

1 个答案:

答案 0 :(得分:0)

我建议将Box类编写为View。

Box extends View{
float lig;
float col;
Clolr backGroundColor;

...

@Override
protected void onDraw(Canvas canvas) {
//draw here on canvas
...
}

public drawBox(int backGroundColor, int lig, int col){

    this.aView = aView;
    this.lig = lig;
    this.col = col;
    this.backGroundColor = backGroundColor;
    invalidate()
}

而不是添加构造函数,添加一个方法来设置框值,并在设置值后调用invalidate()。