Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Canvas draw area transparent in android?

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

like image 344
Karthik Avatar asked Jan 02 '12 17:01

Karthik


People also ask

How do I change transparency in paint android?

You can use the Alpha property of Paint class. myPaint. setAlpha(10); will help you. It appears alpha must be set only after the style is set to FILL.

What is the color code for transparent in canvas?

#0000ffff - that is the code that you need for transparent.


2 Answers

You can create a Bitmap of the same size as the canvas. Erase all the colors of the bitmap using Color.TRANSPARENCY and set it as a canvas bitmap:

Bitmap transparentBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(),
Bitmap.Config.ARGB_8888);
transparentBitmap.eraseColor(Color.TRANSPARENT);
canvas.setBitmap(transparentBitmap);
like image 183
Michał Wołodkiewicz Avatar answered Nov 08 '22 23:11

Michał Wołodkiewicz


this make canvas tramsparent and it is work for me :)

canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.OVERLAY);
like image 45
Muneebq Ashfaq Avatar answered Nov 09 '22 01:11

Muneebq Ashfaq