android 中的layer图层

时间:2021-08-13 04:13:25

android 中的layer图层

canvas.saveLayer()、saveLayerAlpha()讲一个图层入栈,我的理解是新建一个图层和一个有alpha的图层。restore、restoreToCount()方法将一个图层出栈,合并图层的意思。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyLayer(this));
}

public class MyLayer extends View {

private Paint mPaint;
private static final int LAYER_FLAGS =
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;

public MyLayer(Context context) {
super(context);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
mPaint.setColor(Color.BLUE);
canvas.drawCircle(150, 150, 100, mPaint);

canvas.saveLayerAlpha(0, 0, 400, 400, 127, LAYER_FLAGS);//相当于新建一个alpha127的透明图层
mPaint.setColor(Color.RED);
canvas.drawCircle(200, 200, 100, mPaint);
canvas.restore();
}
}
}