Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a SurfaceView?

I've extended SurfaceView and managed to draw it in an Activity. The Activity should be able to call a method on my SurfaceView that changes some parameter and redraws it. How can that update function be implemented?

This is my class:

public class MySurfaceView extends SurfaceView
                                    implements SurfaceHolder.Callback {

    private int circleRadius = 50;
    private SurfaceHolder sh;
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public MySurfaceView(Context context, AttributeSet as) {
        super(context,as);
        sh = getHolder();
        sh.addCallback(this);
        paint.setColor(Color.BLUE);
        paint.setStyle(Style.FILL);
    }
    public void surfaceCreated(SurfaceHolder holder) {
        Canvas canvas = sh.lockCanvas();
        canvas.drawColor(Color.BLACK);
        canvas.drawCircle(100, 200, circleRadius, paint);
        sh.unlockCanvasAndPost(canvas);
    }
    public void update( newRadius ) {
        circleRadius = newRadius;
        // What more?
    }
}

What should update contain to redraw everything? Does this have to do with surfaceChanged?

like image 489
Andreas Avatar asked Sep 04 '13 06:09

Andreas


People also ask

What is a SurfaceView in Android?

Provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen.

What is SurfaceHolder callback?

An implementation of SurfaceView that uses the dedicated surface for displaying OpenGL rendering. NativeActivity. Convenience for implementing an activity that will be implemented purely in native code.

What is a surface holder?

Surface objects enable apps to render images to be presented on screens. SurfaceHolder interfaces enable apps to edit and control surfaces.


1 Answers

  • The update function should call invalidate() or postInvalidate() in order for the View to redraw.
  • Further, redrawing is disabled by default for SurfaceViews. Enable it by calling setWillNotDraw(false) in e.g. surfaceCreated.
like image 56
Andreas Avatar answered Oct 12 '22 18:10

Andreas