Set Background color of Surface View

守給你的承諾、 提交于 2019-11-30 18:42:45

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.

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

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.

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

Use this

surfaceview.getHolder().setFormat(PixelFormat.TRANSLUCENT);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!