为什么在android中调用canvas.drawRect时只绘制一个矩形?

时间:2016-04-23 11:59:35

标签: java android android-canvas draw rect

我正在尝试使用foreach循环为ArrayList中的每个字符串绘制一个矩形,但它似乎只绘制了最后一个矩形。

我看过类似的问题,但他们遇到的问题包括矩形底部高于顶部并调用drawPaint - 但我没有这些问题。

MainActivity.java

public class MainActivity extends AppCompatActivity {

ArrayList<String> ideas = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the icon
    ActionBar actionBar = getSupportActionBar();
    assert actionBar != null;
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.drawable.actionbarfull);

    //Use API in future to GET all ideas
    ideas.add("Idea 1");
    ideas.add("Idea 2");
    ideas.add("Idea 3");
    setContentView(new IdeaRectangle(this, ideas));
}

}

IdeaRectangle.java

public class IdeaRectangle extends View {

Rect rectangle = new Rect();
Paint mBlue = new Paint();
Paint textPaint = new Paint();
ArrayList<String> ideasToDraw = new ArrayList<>();
int gap = 50;
int sidegap = 30;
int right = 0;
int height = 250;
int top = 0;
int bottom = 0;
int counter = 0;

public IdeaRectangle(Context context) {
    super(context);
}

public IdeaRectangle(Context context, ArrayList<String> ideas) {
    super(context);
    ideasToDraw = ideas;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // Setting colour of rectangle and text
    mBlue.setARGB(255, 0, 183, 255);
    textPaint.setTextSize(50);
    textPaint.setARGB(255, 0, 0, 0);
    ArrayList<Rect> rectangles = drawIdea(canvas, ideasToDraw);

    for (Rect rectangle : rectangles) {
        // Draw rectangle
        canvas.drawRect(rectangle, mBlue);
        canvas.drawText("This is an idea. There were " + rectangles.size() + " rectangles.", rectangle.left, rectangle.centerY(), textPaint);
    }
}

private ArrayList<Rect> drawIdea(Canvas canvas, ArrayList<String> ideas) {

    ArrayList<Rect> rectangles = new ArrayList<>();
    right = canvas.getWidth() - sidegap;

    for (String idea : ideas) {
        // Setting location of rectangle
        top = gap + (counter * (gap + height));
        bottom = top + height;
        counter++;

        System.out.println(sidegap + "," + top + "," + right + "," + bottom);
        rectangle.set(sidegap, top, right, bottom);
        rectangles.add(rectangle);
    }
    return rectangles;
}

打印出矩形尺寸的控制台日志打印出来:

04-23 12:47:44.920 11005-11005/? I/System.out: 30,50,1050,300
04-23 12:47:44.920 11005-11005/? I/System.out: 30,350,1050,600
04-23 12:47:44.920 11005-11005/? I/System.out: 30,650,1050,900

0 个答案:

没有答案