2

I want to put a transparent SurfaceView on top of an ImageView. I have the following in the SurfaceView subclass constructor

setZOrderOnTop(true);    // necessary
SurfaceHolder h = getHolder();
h.setFormat(PixelFormat.TRANSPARENT);

I also have this in the beginning of the onDraw() function

canvas.drawColor( 0, PorterDuff.Mode.CLEAR );

Yet, all I get is a black background which blocks the image.

Any ideas?

PS, I also tried this instead of drawColor(), but to no avail

Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
user1692811
  • 43
  • 1
  • 4

2 Answers2

2

I know, that this post is a year old, but you set the color to 0, which stands for black. Use

canvas.drawColor( Color.TRANSPARENT, PorterDuff.Mode.CLEAR );

to make it transparent.

mexok
  • 89
  • 1
  • 8
  • This works if it is a View, but as @adamp says above, SurfaceView involves a whole different method of doing things. Simply setting the background to transparent won't work. What you can do is `surfaceView.setZOrderOnTop(true)`, which will allow the stuff behind the SurfaceView to show through. This can create other problems, however, like if you have a Nav Drawer; the SurfaceView will also be on top of the drawer. – David John Welsh Jul 31 '15 at 02:13
1

SurfaceViews cannot be transparent in this way. Try a SurfaceTexture if you're on API 11 or above, or draw into a regular View in other cases.

A SurfaceView is a special case that coordinates surface compositing in a special way optimized for performance. You can draw content on top of a SurfaceView in your view hierarchy if configured for it, but you cannot blend a SurfaceView's content with content behind it.

adamp
  • 28,862
  • 9
  • 81
  • 69
  • First, thanks for the reply. From this question: http://stackoverflow.com/questions/5391089/how-to-make-surfaceview-transparent I thought that it's possible. Do you have an example of how to use a simple view, to mimic SurfaceView functionality? – user1692811 Sep 23 '12 at 19:56
  • What is it that you're actually trying to do? Why do you have a SurfaceView on top of an ImageView? What's the use case? – adamp Sep 23 '12 at 19:59
  • I want to draw some shapes over an image. I changed the code to subclass View, and used invalidate() after to force draw. Seems to be working fine. Thanks again. – user1692811 Sep 23 '12 at 20:05
  • Yes, if that's all you want to do, that's the way to go. SurfaceView pulls in a lot of other things to worry about that you don't need for such a simple case. Glad you got it! – adamp Sep 23 '12 at 20:07
  • This is my first post, so I can't vote you up. Hopefully others will do, so others won't get confused on this subject. – user1692811 Sep 23 '12 at 20:13