ImStupid
ImStupid

Reputation: 35

How to draw this line in Activity?

i composed this code to animate a drawing line out of multiple examples i found here on stack:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new DrawLine(this));
}

private static class DrawLine extends View {

    public DrawLine(Context context) {
        super(context);
        setFocusable(true);
    }


    private int startX = 0;
    private int startY = 0;

    private int endX = 0;
    private int endY = 0;

    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG) {
        {
            setDither(true);
            setColor(Color.RED);
            setStrokeWidth(40);
        }
    };

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

        canvas.drawLine(startX, startY, endX, endY, paint);

        if (endX != 300 && endY != 300) {
            endY++;
            endX++;

            postInvalidateDelayed(0); //
        }
    }

}
}

My question is, how can i draw this line across my MainActivity xml instead of setting the contentView with the DrawLine class? Also, is there any way to make the line draw quicker?

Thanks!

Upvotes: 0

Views: 173

Answers (2)

Ebin Chandy
Ebin Chandy

Reputation: 25

Sorry but this code is in kotlin . I don't know java .

var delay=0
var startX=0
var startY=0
var xgap=5
var ygap=5
for (i in 1..50){
            delay+=3
            handler.postDelayed(Runnable {
                canvas.drawLine(
                        startX,
                        startY,
                        stopX,
                        stopY,
                        paint)
                startX=stopX
                startY=stopY
                stopX+=xgap
                stopY+=ygap


            },delay)

You will get the idea. Increment a delay and location each time I have done this in my app and it is working

Edit: you can convert this code to java in android studio itself

Upvotes: 0

Ebin Chandy
Ebin Chandy

Reputation: 25

I think this is not working because endX and endY gets increments only once. Try giving direct values and check if it works

Upvotes: 1

Related Questions