如何使用画布设置绘制线的延迟

时间:2016-04-28 10:31:43

标签: java android canvas android-canvas paint

是Android平台的新手,并试图为每个像素绘制延迟线。但是当执行代码时,他们没有延迟每个像素,他们将在完整循环执行后显示,我不知道为什么这样做。我需要延迟每个像素,我的意思是在实时视图中绘制像素到像素。有可能请提供示例代码或示例。谢谢你。

  

活性

public class MainActivity extends Activity {

ImageView drawingImageView;
int x1 = 50;
int y1 = 100;
int y2 = 100;
int i;

@Override
public 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.GREEN);
    paint.setStrokeWidth(5);
    for (i = 0; i < 250; i++) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException ie) {
            //error;
        }
        canvas.drawLine(x1, y1, x1 + i, y2, paint);
    }
    i++;
}}

1 个答案:

答案 0 :(得分:1)

请通过这个。希望这对你有用。 :)

公共类TestActivity扩展了AppCompatActivity {

ImageView drawingImageView;
int x1 = 50;
int y1 = 100;
int y2 = 100;
int x2=50, mCount = 1;
private Handler mHandler;
private Runnable mRunnable;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
            .getDefaultDisplay().getWidth(), (int) getWindowManager()
            .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);

    final Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setStrokeWidth(5);

    canvas.drawLine(x1, y1, x2, y2, paint);

    mHandler = new Handler(getMainLooper());
    mRunnable = new Runnable() {
        @Override
        public void run() {
            int x3 = x2 + mCount;
            canvas.drawLine(x2, y1, x3, y2, paint);
            x2 = x3;
            mCount++;
            drawingImageView.invalidate();
            if (mCount < 150)
                mHandler.postDelayed(mRunnable, 50);
        }
    };

    mHandler.postDelayed(mRunnable,50);


}

}