Android Canvas saveLayerAlpha使用

Canvas.saveLayerAlpha(float left, float top, float right, float bottom, int alpha, int saveFlags)

本身和save方法差不多,但是它单独分配了一个画布用于绘制图层。它定义了一个画布区域(可设置透明度),此方法之后的所有绘制都在此区域中绘制,直到调用canvas.restore()方法。例如:在调用saveLayerAlpha方法之前绘制了一个“圆形”,在调用saveLayerAlpha方法之后绘制了一个“圆形”此时这两个圆形并不在同一个图层。下面给出一个例子以及样图来说明这个问题。

实例代码:

package cn.yw.lib.graphics;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class LayerActivity extends Activity{
    private LayerView view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = new LayerView(this);
        setContentView(view);
    }
    /**
     * 测试图层
     * @author yw-tony
     *
     */
    class LayerView extends View{
        private Paint paint;
        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 LayerView(Context context) {
            super(context);
            paint = new Paint();
            paint.setAntiAlias(true);
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //清屏操作
            canvas.drawColor(Color.GRAY);
            //画布向右下移动50像素
            canvas.translate(50, 50);
            paint.setColor(Color.RED);
            canvas.drawCircle(50, 50, 25, paint);
            canvas.saveLayerAlpha(0, 0, 200, 200, 0x88, LAYER_FLAGS);
            paint.setColor(Color.GREEN);
            canvas.drawCircle(60, 60, 25, paint);
            canvas.restore();
        }
    }
}

样图:

 

posted on 2014-03-05 10:28  飘杨......  阅读(4886)  评论(0编辑  收藏  举报