我想在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为黑色,没有显示图片 问题在哪里?
答案 0 :(得分:0)
使用您的代码,x和y在每次迭代时重置为0 ... 您必须在while循环之外移动x和y的初始化:
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;
}
}