Gradient appears banded in a SurfaceView, but look

2019-01-15 10:00发布

问题:

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.

Any suggestions, please?

Trev

回答1:

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

getHolder().setFormat(PixelFormat.RGBA_8888);