wingsraam wingsraam - 7 months ago 15
Java Question

How to draw line bitmap step by step at run time in the activity

I have sample code for draw line. I need line draw point by point for run time. But now I got line after execution only showing activity. But, I need to start activity and show the line point by point.

Sample code

public class MainActivity extends ActionBarActivity {

ImageView drawingImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);

// Line
Paint paint = new Paint();
paint.setColor(Color.rgb(255, 153, 51));
paint.setStrokeWidth(10);
int startx = 50;
int starty = 90;
int endx = 350;
int endy = 90;
while(endx>=startx) {
try {
Thread.sleep(5);
}catch (InterruptedException e){
e.printStackTrace();
}
canvas.drawLine(startx, starty, startx+1, endy, paint);
startx++;
}
}}


XML

<?xml version="1.0" encoding="utf-8"?>




<ImageView android:id="@+id/DrawingImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />



Answer

Use Below code to restart animation when its reach the endx position -

private void ImgAnimation() {

        mHandlerAnimation = new Handler();

        mRunnableAnimation = new Runnable() {
            public void run() {

                  if(endx>startx) 
                  {
                         canvas.drawLine(startx, starty, startx+1, endy, paint);
                         startx = startx + 1;
                         getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
                  }
                  else
                  {
                      bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                      canvas = new Canvas(bitmap);
                      drawingImageView.setImageBitmap(bitmap);
                      startx = 50;
                  }


                mHandlerAnimation.postDelayed(this, 80);
            }
        };

        mHandlerAnimation.postDelayed(mRunnableAnimation, 80);

    }