HI!我在水平滚动视图中有一个surfaceView,我希望用onDraw()调用来填充图像。但是,没有任何内容。 我有一个类,其中绘图是从线程CanvasThread完成的。
public class PanelChart extends SurfaceView implements SurfaceHolder.Callback {
private CanvasThread canvasthread ;
public PanelChart(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
canvasthread = new CanvasThread(getHolder(), this);
setFocusable(true);
我试图改变
`synchronized (_surfaceHolder) {
_panel.postInvalidate();
}`
要
synchronized (_surfaceHolder) {
_panel.postInvalidate();
}
我还试图在没有运气的情况下添加调用setWillNotDraw(false):
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
canvasthread.setRunning(true);
canvasthread.start();
setWillNotDraw(false);
这似乎是一个常见问题,但我遇到的解决方案都没有对我有用。
谢谢!
答案 0 :(得分:3)
postInvalidate不会使用surfaceView调用onDraw。你需要解锁画布,绘制东西然后锁定画布。以下是surfaceView的一个线程示例:
class CanvasThread extends Thread {
private SurfaceHolder surfaceHolder;
private PanelChart panel;
private boolean run = false;
public CanvasThread(SurfaceHolder surfaceHolder, PanelChart panel) {
this.surfaceHolder = surfaceHolder;
this.panel = panel;
}
public void setRunning(boolean run) {
this.run = run;
}
public SurfaceHolder getSurfaceHolder() {
return surfaceHolder;
}
@Override
public void run() {
Canvas c;
while (run) {
c = null;
//limit the frame rate to maximum 60 frames per second (16 miliseconds)
timeNow = System.currentTimeMillis();
timeDelta = timeNow - timePrevFrame;
if ( timeDelta < 16){
try{
Thread.sleep(16 - timeDelta);
}catch(InterruptedException e){
}
}
timePrevFrame = System.currentTimeMillis();
try {
c = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
panel.onDraw(c); //draw canvas
computePhysics(); //calculate next frame
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c); //show canvas
}
}//try finally
} //while
}//run
}//thread