Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradient appears banded in a SurfaceView, but looks very smooth in a normal View

My problem is that when drawing a simple test image (a rectangle with a gradient fill) within a SurfaceView, the gradient has colour banding. When drawing exactly the same rectangle with the same gradient in a simple extended View, the gradient looks very smooth, and as nice as I would expect for 32-bit colour.

This is occurring side by side using the test SurfaceView placed alongside the test View within the same layout in the same Activity.

For information, in the Activity class I am calling window.setFormat(PixelFormat.RGBA_8888) to switch the Activity to 32-bit colour, as this was the solution in the past to eliminate banding in gradients (however, I believe that this is no longer necessary at a certain Android level, where 32-bit is the default). My minSdkVersion is 8.

The test code that appears in the onDraw() of both the simple extended View and the SurfaceView is:

    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setAntiAlias(false);
    paint.setFilterBitmap(false);
    paint.setDither(false); 
    Shader shader = new LinearGradient(
            0,
            0,
            0,
            200,
            new int[]{0xff150d2f,0xff432b96},
            null,
            Shader.TileMode.CLAMP
            );

    paint.setShader(shader);    
    canvas.drawRect(0,0,getWidth(),getHeight(), paint);

Here is the screenshot showing the SurfaceView above and the normal View beneath. I realise that the banding is very subtle in this example; it's even more apparent when the gradient sweeps over a smaller band of colours.

Screenshot

Any suggestions, please?

Trev

like image 856
Trevor Avatar asked Oct 15 '11 00:10

Trevor


1 Answers

Found the solution myself in the end by adding this into the SurfaceView's constructor:

getHolder().setFormat(PixelFormat.RGBA_8888);
like image 64
Trevor Avatar answered Nov 08 '22 00:11

Trevor