多个矩形不在画布上绘图

Man*_*ika 8 android drawrect family-tree android-canvas

我试图在android中创建一个类似于结构的家族树.我正在使用画布为家庭成员名称和连接线绘制矩形和线条.

我在链接的帮助下通过以下方法绘制矩形和线条

DrawView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;

public class DrawView  extends View {
    Paint paint = new Paint();
    float mx,  my,  mdensity;
    Paint mBGPaint, mTXTPaint,mLINEPaint,mBRDPaint;
    String text;
    public DrawView(Context context, float x, float y, float density, String text) {
        super(context);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(8);
        paint.setStyle(Paint.Style.STROKE);

        mx = x;
        my = y;
        mdensity = density;
        this.text = text;
    }
    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        init();

        mLINEPaint.setStrokeWidth(8);

        //draw rect border
        canvas.drawRect(100, 100, 200, 200, mBRDPaint);
//        //draw text
        canvas.drawText(text, 150, 150, mTXTPaint);
//        //draw line

        float x = mx+150;

        canvas.drawLine(x, 10, x, 100, mLINEPaint);

    }
    public void init() {

        //rectangle background
        mBGPaint = new Paint();
        mBGPaint.setColor(Color.parseColor("#80123456"));

        //your text
        mTXTPaint = new Paint();
        mTXTPaint.setColor(Color.parseColor("#123456"));

        //your line
        mLINEPaint = new Paint();
        mLINEPaint.setColor(0xFFFF00FF);

        //rectangle border
        mBRDPaint = new Paint();
        mBRDPaint.setStyle(Paint.Style.STROKE);
        mBRDPaint.setStrokeWidth(10);
        mBRDPaint.setColor(Color.parseColor("#80123456"));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试在LinearLayout中添加多个视图,其方向水平如下:

  float density = getApplicationContext().getResources().getDisplayMetrics().density;
  DrawView drawView;

  float x = 100, y = 200;
  int count1 = 1;
  int id;
  LinearLayout  layout2 = new LinearLayout(this);

  layout2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
  layout2.setOrientation(LinearLayout.HORIZONTAL);

  main_layout.addView(layout2);

  DrawView drawView1;
  CircleView circleView;
  for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {

      String key = entry.getKey();
      if (count1 < 2) {
          x = dirButton.getX();
          y = dirButton.getY();
      }
      drawView1 = new DrawView(this, x, y, density, key);
      drawView1.setId(butId++);
      drawView1.setLayoutParams(params);
      layout2.addView(drawView1);

      count1++;
      x = x + 100;
  }
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,只有一个视图被添加到画布而其他视图不可见.我没有在android中使用canvas的经验,如果有人可以指导我解决这个问题,我会很高兴.

W4R*_*0CK 0

我尝试处理你的项目,但它太宽泛,无法在答卷上编辑。我必须建议看看这些:

  1. 多个矩形
  2. 有视图的矩形