0

我想在我的 MainActivity 中绘制动画图片我的 MainActivity 代码如下:

public class LaozhangActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    Ch0_1 view=new Ch0_1(this);
    super.onCreate(savedInstanceState);
    setContentView(view);


}
}

我已经定义了一个扩展类SurfaceView以显示动画图片;代码是这样的:

public class Ch0_1 extends SurfaceView implements Callback, Runnable
{

SurfaceHolder surfaceHolder;

private boolean isThreadRunning = true;

Canvas canvas;
float r = 10;

public Ch0_1(Context context)
{

 super(context);

    surfaceHolder = this.getHolder();

    surfaceHolder.addCallback(this);
    canvas=new Canvas();
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height)
{

}

public void surfaceCreated(SurfaceHolder holder)
{

    new Thread(this).start();
}

public void surfaceDestroyed(SurfaceHolder holder)
{

}


private void Method(int x,int y)
{

    Paint pen=new Paint();
    pen.setColor(Color.GREEN);

    canvas=surfaceHolder.lockCanvas();
    canvas.drawLine(0, 0, x, y, pen);
    surfaceHolder.unlockCanvasAndPost(canvas);

}

 public void run()
 {
    while (isThreadRunning)
    {
     int x=0,y=0;
     Method(x,y);
        try
        {
            Thread.sleep(100);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        x+=10;
        y+=10;
        if(x>400)break;
    }
}
}

运行时MainActivity是黑色的,没有显示图片。
问题出在哪里?

4

1 回答 1

0

使用您的代码,每次迭代时 x 和 y 都重置为 0 ...您必须将 x 和 y 的初始化移到 while 循环之外:

    public void run() {
        int x = 0, y = 0;
        while (isThreadRunning) {
            Method(x, y);
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            x += 10;
            y += 10;
            if (x > 400)
                break;
        }
    }
于 2012-10-31T08:58:46.757 回答