2011-12-05 25 views
7

tengo diseño simple¿Cómo hacer SurfaceView con fondo transparente?

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/RelativeLayout1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/backgroundtimer" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/TextView1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:text="@string/hello" /> 

    <com.fmech.zenclock.surface.ZenClockSurface 
     android:id="@+id/zenClockSurface1" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true"/> 

</RelativeLayout> 

y A tienen clase ZenClockSurface

package com.fmech.zenclock.surface; 

import android.content.Context; 
import android.content.res.Resources; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Matrix; 
import android.graphics.Paint; 
import android.graphics.Paint.Style; 
import android.graphics.PixelFormat; 
import android.util.AttributeSet; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class ZenClockSurface extends SurfaceView implements SurfaceHolder.Callback{ 

    private DrawClock drawClock; 

    public ZenClockSurface(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     this.getHolder().setFormat(PixelFormat.TRANSLUCENT); 
     getHolder().addCallback(this); 
    } 

    public ZenClockSurface(Context context) { 
     super(context); 
     this.getHolder().setFormat(PixelFormat.TRANSLUCENT); 
     getHolder().addCallback(this); 
    } 

    public ZenClockSurface(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     this.getHolder().setFormat(PixelFormat.TRANSLUCENT); 
     getHolder().addCallback(this); 
    } 

    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, 
      int height) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
     //this.getHolder().setFormat(PixelFormat.TRANSPARENT); 
     drawClock = new DrawClock(getHolder(), getResources()); 
     drawClock.setRunning(true); 
     drawClock.start(); 

    } 

    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) { 
     boolean retry = true; 
     // завершаем работу потока 
     drawClock.setRunning(false); 
     while (retry) { 
      try { 
       drawClock.join(); 
       retry = false; 
      } catch (InterruptedException e) { 
      } 
     } 

    } 

    class DrawClock extends Thread{ 
     private boolean runFlag = false; 
     private SurfaceHolder surfaceHolder; 
     private Bitmap picture; 
     private Matrix matrix; 
     private long prevTime; 
     private Paint painter; 

     public DrawClock(SurfaceHolder surfaceHolder, Resources resources){ 
      this.surfaceHolder = surfaceHolder; 

      this.surfaceHolder.setFormat(PixelFormat.TRANSLUCENT); 
      picture = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher); 

      matrix = new Matrix(); 
      this.painter=new Paint(); 
      this.painter.setStyle(Paint.Style.FILL); 

     } 

     public void setRunning(boolean run) { 
      runFlag = run; 
     } 

     @Override 
     public void run() { 
      Canvas canvas; 
      while (runFlag) { 

        matrix.preRotate(1.0f, picture.getWidth()/2, picture.getHeight()/2); 
       canvas = null; 
       try { 
        //surfaceHolder.getSurface().setAlpha(0.5f); 
        canvas = surfaceHolder.lockCanvas(null); 
        synchronized (surfaceHolder) { 

         canvas.drawColor(Color.TRANSPARENT); 

         canvas.drawBitmap(picture, matrix, this.painter); 
        } 
       } 
       finally { 
        if (canvas != null) { 
         surfaceHolder.unlockCanvasAndPost(canvas); 
        } 
       } 
      } 
     } 
    } 
} 

Y el código de la actividad

package com.fmech.zenclock.surface; 

import android.app.Activity; 
import android.graphics.PixelFormat; 
import android.os.Bundle; 

public class ZenClockSurfaceActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     getWindow().setFormat(PixelFormat.TRANSLUCENT); 
     setContentView(R.layout.main); 


    } 
} 

Quiero lo que el color de fondo de la imagen androide era tranparent pero consigo negro fondo.

Tengo antecedentes sobre RelativeLayout con alguna imagen bu SurfaceView gira el ícono de Android sin transparencia.

¿Cómo puedo hacer transparente?

+0

Olvidé agregar this.getHolder(). SetFormat (PixelFormat.TRANSLUCENT); en ambos del constructor – Rasel

Respuesta

25

Sí, lo hice, resolver el problema

Código de actividad

package com.fmech.zenclock.surface; 

import android.app.Activity; 
import android.graphics.PixelFormat; 
import android.os.Bundle; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class ZenClockSurfaceActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     ZenClockSurface sfvTrack = (ZenClockSurface)findViewById(R.id.zenClockSurface1); 
     sfvTrack.setZOrderOnTop(true); // necessary 
     SurfaceHolder sfhTrack = sfvTrack.getHolder(); 
     sfhTrack.setFormat(PixelFormat.TRANSLUCENT); 

    } 
} 

Código superficie

package com.fmech.zenclock.surface; 

import android.content.Context; 
import android.content.res.Resources; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Matrix; 
import android.graphics.Paint; 
import android.graphics.Paint.Style; 
import android.graphics.PixelFormat; 
import android.graphics.Region; 
import android.util.AttributeSet; 
import android.view.Surface.OutOfResourcesException; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class ZenClockSurface extends SurfaceView implements 
     SurfaceHolder.Callback { 

    private DrawClock drawClock; 

    public ZenClockSurface(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     getHolder().addCallback(this); 
    } 

    public ZenClockSurface(Context context) { 
     super(context); 
     getHolder().addCallback(this); 
    } 

    public ZenClockSurface(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     getHolder().addCallback(this); 
    } 

    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, 
      int height) { 

    } 

    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
     drawClock = new DrawClock(getHolder(), getResources()); 
     drawClock.setRunning(true); 
     drawClock.start(); 

    } 

    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) { 
     boolean retry = true; 
     drawClock.setRunning(false); 
     while (retry) { 
      try { 
       drawClock.join(); 
       retry = false; 
      } catch (InterruptedException e) { 
      } 
     } 

    } 

    class DrawClock extends Thread { 
     private boolean runFlag = false; 
     private SurfaceHolder surfaceHolder; 
     private Bitmap picture; 
     private Matrix matrix; 
     private Paint painter; 

     public DrawClock(SurfaceHolder surfaceHolder, Resources resources) { 
      this.surfaceHolder = surfaceHolder; 

      picture = BitmapFactory.decodeResource(resources, 
        R.drawable.ic_launcher); 
      matrix = new Matrix(); 
      this.painter = new Paint(); 
      this.painter.setStyle(Paint.Style.FILL); 
      this.painter.setAntiAlias(true); 
      this.painter.setFilterBitmap(true); 
     } 

     public void setRunning(boolean run) { 
      runFlag = run; 
     } 

     @Override 
     public void run() { 
      Canvas canvas; 
      while (runFlag) { 


       matrix.preRotate(1.0f, picture.getWidth()/2, 
         picture.getHeight()/2); 
       canvas = null; 
       try { 
        canvas = surfaceHolder.lockCanvas(null); 
        synchronized (surfaceHolder) { 
         canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR); 
         canvas.drawBitmap(picture, matrix, this.painter); 
        } 
       } catch (IllegalArgumentException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } finally { 
        if (canvas != null) { 
         surfaceHolder.unlockCanvasAndPost(canvas); 
        } 
       } 
      } 
     } 
    } 
} 

Es trabajo.

+1

drawColor (0, android.graphics.PorterDuff.Mode.CLEAR); muchas gracias, ¡he estado buscando esto por horas! pensé dibujarColor (Color.TRANSPARENTE); funcionará ... pero no fue así, ¡tu solución me salvó ...! – tom91136

+0

No funcionó para mí. Establecí el fondo del diseño para que sea de color # f0f0f0, pero el fondo de la vista de superficie aún permanecía negro. – Genry

+0

@Dmitry Nelepov: Intenté el mismo código. pero no funcionó para mí El color de la vista de superficie sigue siendo negro. – user2085965

3

En API 3 y 4, no se puede poner nada detrás de SurfaceView. Citando Dianne Hackborn:

vista La superficie es en realidad detrás de la ventana, y un agujero perforado en la ventana para que lo veas. De este modo, puede colocar las cosas encima en su ventana, pero nada en su ventana puede aparecer detrás de ella.

http://groups.google.com/group/android-developers/browse_thread/thread/8d88ef9bb22da574


De API 5 en adelante se puede utilizar setZOrderOnTop. El truco es que usted tiene que hacerlo en su constructor por lo que es llamado antes de la vista se fija a la ventana:

public ZenClockSurface(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    setZOrderOnTop(true); 

    SurfaceHolder holder = getHolder(); 
    holder.setFormat(PixelFormat.TRANSLUCENT); 
} 
+0

No corrijo. Los siguientes cambios en la actividad hacen que SorfaceView sea transparente public void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.main); ZenClockSurface sfvTrack = (ZenClockSurface) findViewById (R.id.zenClockSurface1); sfvTrack.setZOrderOnTop (verdadero); // necesario SurfaceHolder sfhTrack = sfvTrack.getHolder(); sfhTrack.setFormat (PixelFormat.TRANSLUCENT); } –

+0

pero todavía tengo problemas, ahora resulta, el sitio donde estaba la imagen es negra. –

+0

Gracias por señalar 'setZOrderOnTop', Rainwork! He editado mi respuesta. Avíseme si funciona para usted. – chiuki

Cuestiones relacionadas