gpt4 book ai didi

java - 如何以编程方式连续绘制多个矩形?

转载 作者:太空狗 更新时间:2023-10-29 13:26:40 24 4
gpt4 key购买 nike

我想把几个矩形排成一排。但是因为我是 Android 新手,特别是 Bitmap、Canvas 等,我需要一些帮助。

它应该看起来像这样,只有矩形:

enter image description here

我用这段代码创建了一个矩形:

        Paint paint = new Paint();
paint.setColor(Color.parseColor("#CD5C5C"));
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bg);
canvas.drawRect(50, 80, 200, 200, paint);
RelativeLayout ll = (RelativeLayout) findViewById(R.id.rect);

ImageView iV = new ImageView(this);
iV.setImageBitmap(bg);

ll.addView(iV);

但现在我不知道如何连续创建更多不同颜色的矩形。我真的很新,很抱歉这个可能很愚蠢的问题,但我需要帮助。

谁能指导我如何以最好的方式做到这一点?

最佳答案

这里的关键是这些行:

paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(50, 80, 200, 200, paint);

他们设置颜色并绘制一个矩形。您现在可以重复这些行以获得 2 个矩形:

paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(50, 80, 200, 200, paint);
paint.setColor(Color.parseColor("#DDDDDD"));
canvas.drawRect(210, 80, 360, 200, paint);

请注意,我稍微更改了颜色和坐标。您可以继续多次执行此操作以绘制所有矩形。

更好的方法是为 x 和 y 坐标使用一个变量,并使用一个循环:

int left = 50; // initial start position of rectangles (50 pixels from left)
int top = 50; // 50 pixels from the top
int width = 150;
int height = 150;
for (int row = 0; row < 2; row++) { // draw 2 rows
for(int col = 0; col < 4; col++) { // draw 4 columns
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(left, top, left+width, top+height, paint);
left = (left + width + 10); // set new left co-ordinate + 10 pixel gap
// Do other things here
// i.e. change colour
}
top = top + height + 10; // move to new row by changing the top co-ordinate
}

希望对您有所帮助。

关于java - 如何以编程方式连续绘制多个矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20611277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com