TheYogi
TheYogi

Reputation: 1026

Drawing line programmatically on a Layout

enter image description here

The red Margin represents an AbsoluteLayout, I have and arbitrary number of 'Board' objects placed on the screen. All I want is to draw a line on the screen using the coordinates of the Board object and the center of the screen. Each board object is responsible to draw this line.

Also I want the line to be behind the Board objects I'm guessing I have to change the z-index, or maybe draw the line on the AbsoluteLayout?

I have something like this:

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);
}

}

Upvotes: 1

Views: 2356

Answers (1)

Per-Erik Bergman
Per-Erik Bergman

Reputation: 385

first af all,

you should never ever use the absolute layout, it is deprecated for a good reason.

With that said you have two options. For both options you need to implement your own Layout.

For option no. 1 you can override the dispatchDraw(final Canvas canvas) see below.

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.
   }

    ...

}

Option no. 2 If you like the drawing to occur in the onDraw me you need to set setWillNotDraw(false); since by default the onDraw method on ViewGroups won't be called.

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.
    }

}

Upvotes: 1

Related Questions