I have a requirement something like this , I want to drawpath in android in a canvas and for that I have developed a code. This is the view class.
public class MyView extends View {
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
path.moveTo(100, 100);
path.lineTo(200, 200);
path.lineTo(200, 500);
path.lineTo(400, 500);
path.lineTo(400, 200);
path.lineTo(600, 200);
canvas.drawPath(path, paint);
}
}
This works pretty well and I get the drawpath as I want. Now there is a small tweak, I want the drawpath to appear gradually in a progressive way (say for example the effect a rolling ball will have if it draws a line while rolling left to right, its gradual and slow , but not pausing and drawing).
I tried implementing a Timertask to invalidate the view and draw a fresh view, but that simply pauses and draw, not something I want.
I guess, I have to either add an ObjectAnimator or a ValueAnimator to my code. But I am not sure how to achieve that. Please help
I somehow figured it out how to achieve it. I, however could not directly draw a canvas line with animation though but found out a work around and that actually worked for me. I used a horizontal progress bar instead with a negligible height which will look like a line and then added an Object Animator which will gradually fill the line based on the time i set. I shall share the code for everyone .
In my xml file, I used this,
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:progressDrawable="@drawable/custom_progress"
android:layout_height="2dp"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:max="100"
android:progress="0"
android:layout_marginTop="50dp"
/>
And in my Java file , I used this code
pbr = (ProgressBar)findViewById(R.id.progressBar1);
animation = ObjectAnimator.ofInt(pbr, "progress", 100);
animation.setDuration(2000);
animation.start();
SO in a way, it gives me an effect like the line is drawing progressively. You can try this out and check