2015-09-05 118 views
0

我只是想画一个SurfaceView,并从here绘图画布SurfaceView

修改了一些示例代码,如果我在它的工作循环直接绘制,但是当我调用Draw方法这是行不通的。任何想法可能是什么问题? 但是,这是我在其他教程中看到的,所以它应该工作。 当然我可以使用draw1。但我想知道为什么onDraw在这里不起作用?

public class TestSurefaceView extends Activity { 
MySurfaceView mySurfaceView; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    mySurfaceView = new MySurfaceView(this); 
    setContentView(mySurfaceView); 
} 
class MySurfaceView extends SurfaceView implements Runnable{ 
    Thread thread = null; 
    SurfaceHolder surfaceHolder; 
    volatile boolean running = false; 
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    Random random; 
    public MySurfaceView(Context context) { 
     super(context); 
     surfaceHolder = getHolder(); 
     random = new Random(); 
    } 
    @Override 
    public void run() { 
     while(running){ 
      if(surfaceHolder.getSurface().isValid()){ 
       Canvas canvas = surfaceHolder.lockCanvas(); 
       //draw(canvas); // does not work 
       draw1(canvas); // works 
       surfaceHolder.unlockCanvasAndPost(canvas); 
      } 
     } 
    } 
    private void draw1(Canvas canvas){ 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeWidth(3); 
     int w = canvas.getWidth();int h = canvas.getHeight(); 
     int x = random.nextInt(w-1); 
     int y = random.nextInt(h-1); 
     int r = random.nextInt(255); 
     int g = random.nextInt(255); 
     int b = random.nextInt(255); 
     paint.setColor(0xff000000 + (r << 16) + (g << 8) + b); 
     canvas.drawPoint(x, y, paint); 
    } 
    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     draw1(canvas); 
    } 
} 
} 
+0

你错过了你的'setWillNotDraw(false);'调用某处...... – EpicPandaForce

回答

0

SurfaceViews有两部分,Surface和View。 onDraw()用于在视图上绘图。 Surface的要点是它是一个独立的层,位于视图UI层下方,因此您可以在不影响通常的View无效/重绘循环的情况下对其进行绘制。

很难说,为什么当你没有解释它没有发生时它“不起作用”。定义onDraw()方法时的一个常见问题是,如果View UI得到无效,它将调用该方法在View上绘制。因为视图位于曲面的顶部,所以在视图上绘制的任何东西都会遮挡曲面,例如,一个不透明的背景将防止任何发生在表面上的可见。

我通常建议您不要继承SurfaceView,因为这样做没有价值,而且良好的面向对象操作鼓励组合继承。