如何在 Canvas 上以原始格式绘制更多矩形?

How can I draw more Rectangles in a raw on a Canvas?

我正在做一个测试应用程序,以便将来开发一个更复杂的应用程序,我问自己是否可以在 canvas 上绘制更多的矩形(可能一个左,一个中,一个右).不使用任何 ImageView、TextView 或这些东西。 这是我的代码:

public class MioCanvas extends View {

Paint paint;
Rect rect;

public MioCanvas(Context context) {
    super(context);
    paint = new Paint();
    rect = new Rect();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    paint.setColor(Color.GRAY);
    paint.setStrokeWidth(3);
    canvas.drawRect(0, 1999999, canvas.getWidth() / 2, canvas.getHeight() / 2, paint);
}
}

这里是 activity:

public class MainActivity extends AppCompatActivity {

MioCanvas mioCanvas;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mioCanvas = new MioCanvas(this);
    mioCanvas.setBackgroundColor(Color.GREEN);
    setContentView(mioCanvas);
}
}

例如,要实现您想要的效果,您可以创建一个名为 MyRectangle 的对象,并在其中保留对它的宽度、高度、positionX、positionY、颜色参考等的引用。

在您的 MioCanvas class 中放置一个全局变量,例如:

List<MyRectangle> rectangleList;

在你的构造函数中初始化它,创建几个矩形并将它们添加到列表中。

最后在 onDraw 方法中遍历列表以绘制矩形:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for(MyRectangle rectangle : rectangleList){
        paint.setColor(rectangle.getColour());
        paint.setStrokeWidth(rectangle.getStroke());
        canvas.drawRect(rectangle.getPositionX(), rectangle.getPositionY(), rectangle.getWidth() / 2, rectangle.getHeight() / 2, paint);
    }
}