Home » Android » android – Set Background color of Surface View

android – Set Background color of Surface View

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to set a background color to the surface view to my camera surface view.

I am using this for implementing the same. But this example is not complete. Can anyone please help me with some other useful link.

Thanks

How to&Answers:

There’s a workaround to do this.

  1. add a parent viewgroup for the surfaceview, set the background color to this viewgroup instead of the surfaceview;

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_blue_dark">
    
        <com.example.surfacetest.MySurface
            android:id="@+id/surface"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </FrameLayout>
    
  2. add the following for the SurfaceView instance;

    surfaceView.setZOrderOnTop(true);
    surfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
    

Now you get the background color you want and the surfaceview is tanslucent.

Answer:

use surfaceview_obj.setBackgroundColor (int color) to set background color..

to set white color as background use this code

surfaceview_obj.setBackgroundColor(0Xffffffff);

check this

Answer:

you have to do a little hack-around to make any background work in SurfaceView, like this:

override the setBackground and setBackgroundDrawable methods

   Drawable background

   @Override
   public void setBackgroundDrawable(Drawable background) {
      this.background = background;
   }

   @Override
   public void setBackground(Drawable background) {
      this.background = background;
   }

don’t forget to call setBounds on the drawable

   @Override
   protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
      super.onLayout(changed, left, top, right, bottom);
      matrix = null;
      if (background != null)
         background.setBounds(left, top, right, bottom);
   }

then on the code you’re locking, drawing, unlocking and posting the canvas you add the background

   Canvas c = holder.lockCanvas();
   if (background != null)
      background.draw(c);

   // do your stuff here

   holder.unlockCanvasAndPost(c);

works for both XML and Java backgrounds.

Answer:

just draw a Rect object with canvas.drawRect(). set the co ordinates to 0,0,screenX,screenY

Answer:

Use this

surfaceview.getHolder().setFormat(PixelFormat.TRANSLUCENT);