以编程方式在布局上绘制线条

时间:2017-04-06 02:27:53

标签: android android-canvas

enter image description here

红色保证金代表AbsoluteLayout,我有和任意数量的' Board'放在屏幕上的物体。我想要的是使用Board对象的坐标和屏幕的中心在屏幕上绘制一条线。每个董事会对象负责绘制这一行。

此外,我希望该行在Board对象后面我猜测我必须更改z-index,或者可能在AbsoluteLayout上画线?

我有这样的事情:

public class Board {
ImageView line;  //Imageview to draw line on
Point displayCenter; //Coordinates to the center of the screen
int x;
int y;
Activity activity;

Board(Point p, Point c, Activity activity) // Point c is the coordinates of the Board object
{   
    x = c.x
    y = c.y
    displayCenter.x = p.x;
    displayCenter.y = p.y;
    this.activity = activity;

    updateLine();
}
public void updateLine(){
    int w=activity.getWindowManager().getDefaultDisplay().getWidth();
    int h=activity.getWindowManager().getDefaultDisplay().getHeight();

    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    line.setImageBitmap(bitmap);

    Paint paint = new Paint();
    paint.setColor(0xFF979797);
    paint.setStrokeWidth(10);
    int startx = this.x;
    int starty = this.y;
    int endx = displayCenter.x;
    int endy = displayCenter.y;
    canvas.drawLine(startx, starty, endx, endy, paint);
}

}

1 个答案:

答案 0 :(得分:1)

首先,

你永远不应该使用绝对布局,因为一个充分的理由而被弃用

据说你有两种选择。对于这两个选项,您需要实现自己的布局。

选项号。 1你可以覆盖dispatchDraw(最终的Canvas画布),见下文。

public class CustomLayout extends AbsoluteLayout {

   ...

   @Override
   protected void dispatchDraw(final Canvas canvas) {
       // put your code to draw behind children here.
       super.dispatchDraw(canvas);
       // put your code to draw on top of children here.
   }

    ...

}

选项编号。 2如果你喜欢在onDraw中绘图,你需要设置setWillNotDraw(false);因为默认情况下,ViewGroups上的onDraw方法不会被调用。

public class CustomLayout extends AbsoluteLayout {

    public CustomLayout(final Context context) {
        super(context);
        setWillNotDraw(false);
    }

    ...

    @Override
    protected void onDraw(final Canvas canvas) {
        super.onDraw(canvas);
        // put your code to draw behind children here.
    }

}
相关问题