放置矩形和文本并排Android

本文关键字:Android 文本 | 更新日期: 2023-09-27 18:17:55

我试图将矩形和文本并排放在android画布中。我可以把它们都画出来,但是它们在很多地方重叠。矩形和文本是动态的。我现在的代码是

int left = 50;
int top = 50;
int width = 50;
int height = 50;
for (int row = 0; row < rows; row++) {
    for (int col = 0; col < cols; col++) {
        rectanglePaint.Color = (Color.ParseColor("#CD5C5C"));
        canvas.DrawRect(left, top, left + width, top + height, rectanglePaint);
        left = (left + width + 50);
        rectanglePaint.TextSize = 30;
        canvas.DrawText("Mytext", left, top + height - 10, rectanglePaint);
    }
    top = top + height + 10;
}
有谁能帮我解决这个问题吗?注:我没有足够的声望来发布图片。

编辑:(我的新代码如下):

for (int col = 0; col < 1; col++) { // draw 4 columns
    rectanglePaint.Color = (Color.ParseColor("#CD5C5C"));
    canvas.DrawRect(left, top, left + width, top + height, rectanglePaint);
    left = (left + width + 50);
    string text = "Mytext";
    int spacing = 10;

    canvas.DrawText(text, left, top + height - 10, rectanglePaint);
 left += rectanglePaint.MeasureText(text) + spacing;
    //left = (left + width + 10); // set new left co-ordinate + 10 pixel gap
    //rectanglePaint.TextSize = 30;
    //canvas.DrawText("Mytext",left+5,top+height-10,rectanglePaint);
    // Do other things here
    // i.e. change colour
}

放置矩形和文本并排Android

我想这应该会让你走上正确的道路,如果你改变

canvas.DrawText("Mytext",left,top+height-10,rectanglePaint);

int spacing = 10;
String text = "Mytext";
canvas.DrawText(text,left,top+height-10,rectanglePaint);
left += rectanglePaint.measureText(text) + spacing;

你可能需要改变spacing的值来获得你想要的文本和下一个正方形之间的间距