Can not find Canvas variables in API Level 28

Girish Bhutiya picture Girish Bhutiya · Jan 11, 2019 · Viewed 12k times · Source

The following Canvas Variables are not found in Android 28.

canvas.saveLayer(0, 0, getWidth(), getHeight(), null,
                Canvas.MATRIX_SAVE_FLAG |
                        Canvas.CLIP_SAVE_FLAG |
                        Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
                        Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
                        Canvas.CLIP_TO_LAYER_SAVE_FLAG);

Answer

Cheticamp picture Cheticamp · Jan 15, 2019

Those flags have been removed in API 28. See here:

Class android.graphics.Canvas

Removed Methods int save(int)

Removed Fields int CLIP_SAVE_FLAG
int CLIP_TO_LAYER_SAVE_FLAG
int FULL_COLOR_LAYER_SAVE_FLAG
int HAS_ALPHA_LAYER_SAVE_FLAG
int MATRIX_SAVE_FLAG

That method was deprecated in API 26. See here:

This method was deprecated in API level 26. Use saveLayer(float, float, float, float, Paint) instead.

What to use instead

According to the Canvas source code for API 28, the flags you use all combine to be equal to the value of ALL_SAVE_FLAG:

public  static  final  int ALL_SAVE_FLAG =  0x1F;
public  static  final  int MATRIX_SAVE_FLAG =  0x01;
public  static  final  int CLIP_SAVE_FLAG =  0x02;
public  static  final  int HAS_ALPHA_LAYER_SAVE_FLAG =  0x04;
public  static  final  int FULL_COLOR_LAYER_SAVE_FLAG =  0x08;
public  static  final  int CLIP_TO_LAYER_SAVE_FLAG =  0x10;

From the same source code the call to Canvas#saveLayer(left, top, right, bottom, paint) defaults to using ALL_SAVE_FLAG:

/**  
 * Convenience for {@link #saveLayer(RectF, Paint)} that takes the four float coordinates of the  
 * bounds rectangle. */
public int saveLayer(float left, float top, float right, float bottom, @Nullable Paint paint) {  
    return saveLayer(left, top, right, bottom, paint, ALL_SAVE_FLAG);  
}

So, it looks like your code is equivalent to the following code which you can use as a replacement:

canvas.saveLayer(0, 0, getWidth(), getHeight(), null);

This version of saveLayer() is only available on API 21+. To support lower API levels, use

canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

Where Canvas.ALL_SAVE_FLAG is the same as the or'ed values above.