How to make Canvas draw area transparent in android?

Karthik picture Karthik · Jan 2, 2012 · Viewed 47.6k times · Source

I would like to make Canvas area transparent because I would like to add an Image behind it so that Canvas actions happen above the image.My code for the canvas is here

public class Panel extends SurfaceView implements SurfaceHolder.Callback {

private ViewThread mThread;
private ArrayList<Element> mElements = new ArrayList<Element>();

public Panel(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    getHolder().addCallback(this); 
    mThread = new ViewThread(this); 
} 


public void doDraw(Canvas canvas) {
    canvas.drawColor(Color.TRANSPARENT);
    synchronized (mElements) {
        for (Element element : mElements) {
            element.doDraw(canvas);
        }
    }
}

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

@Override
public void surfaceCreated(SurfaceHolder holder) {
    if (!mThread.isAlive()) {
        mThread = new ViewThread(this);
        mThread.setRunning(true);
        mThread.start();
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    if (mThread.isAlive()) {
        mThread.setRunning(false);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    synchronized (mElements) {
        mElements.add(new Element(getResources(), (int) event.getX(), (int) event.getY()));
    }
    return super.onTouchEvent(event);
}

}

How to achieve it, any snippets on it will be very much helpful.Thanks

Answer

Karthik picture Karthik · Jan 3, 2012

I got the output by this

 public Panel(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    this.setBackgroundColor(Color.TRANSPARENT);                 
    this.setZOrderOnTop(true); //necessary                
    getHolder().setFormat(PixelFormat.TRANSPARENT); 
    getHolder().addCallback(this); 
    mThread = new ViewThread(this); 

}