12

I have a "simple" problem. I try to draw on surfaceview. Layout-XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <SurfaceView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/imagesurface"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:background="#00ff00">
    </SurfaceView>

</LinearLayout>

The Activity is a SurfaceHolder.Callback:

public class OpenCvonAndroidGTDforHOGActivity extends Activity implements SurfaceHolder.Callback{

    private SurfaceHolder _surfaceHolder;
    private SurfaceView _surfaceView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        _surfaceView = (SurfaceView)findViewById(R.id.imagesurface);
        _surfaceHolder = _surfaceView.getHolder();
        _surfaceHolder.addCallback(this);
        _surfaceView.setWillNotDraw(false);

    }

    protected void onDraw(Canvas canvas) {
        canvas.drawRGB(255, 0, 255);            
    }

    public void surfaceCreated(SurfaceHolder holder) {
        Canvas canvas = null;
        try {
            canvas = holder.lockCanvas();
            synchronized(holder) {
                onDraw(canvas);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }


    public void showToast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
}

If i call

_surfaceview.setBackground(Color.RED) in onDraw(...) it works. But

canvas.drawRGB(255, 0, 255) doesn't work :(

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
ChHaupt
  • 363
  • 3
  • 6
  • 17
  • Does this answer your question? [Drawing to a SurfaceView in Android](https://stackoverflow.com/questions/6690898/drawing-to-a-surfaceview-in-android) – General Grievance Aug 29 '22 at 14:16

2 Answers2

4

SurfaceView is composed by a View in your current layout and a surface under your layout. If you set a background to the view, you won't see anything of what is happening on the surface.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
cescom
  • 116
  • 6
-2

Did you try

yourHolder.unlockCanvassAndPost(your_canvas);
Kartoch
  • 7,610
  • 9
  • 40
  • 68
Aytunc MATRAC
  • 95
  • 1
  • 8