Android Paint 之 ComposeShader 组合图片

实现以下效果图

PorterDuff.Mode 模式参考以下链接
Android Paint Xfermode 详解

Android Paint 之 ComposeShader 组合图片_第1张图片

代码

图片居中我们就不计算了,只是做个效果

public class ComposeShaderView extends View {
    //支持的模式
    private PorterDuff.Mode[] modes = {
            PorterDuff.Mode.CLEAR,
            PorterDuff.Mode.SRC,
            PorterDuff.Mode.DST,
            PorterDuff.Mode.SRC_OVER,
            PorterDuff.Mode.DST_OVER,
            PorterDuff.Mode.SRC_IN,
            PorterDuff.Mode.DST_IN,
            PorterDuff.Mode.SRC_OUT,
            PorterDuff.Mode.DST_OUT,
            PorterDuff.Mode.SRC_ATOP,
            PorterDuff.Mode.DST_ATOP,
            PorterDuff.Mode.XOR,
            PorterDuff.Mode.DARKEN,
            PorterDuff.Mode.LIGHTEN,
            PorterDuff.Mode.MULTIPLY,
            PorterDuff.Mode.SCREEN
    };
    //当前模式
    private int mCurIndex = 0;

    ....

    @Override
    protected void onDraw(Canvas canvas) {
        //需要关闭硬件加速(没有关闭则没效果)
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //背景图
        Bitmap bgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.longgui);
        BitmapShader bgBitmapShader = new BitmapShader(bgBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        //覆盖在上面的图
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.wxb);
        //创建一个与背景图一样大的  图标图
        Bitmap newIconBitmap = Bitmap.createBitmap(bgBitmap.getWidth(), bgBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvasIcon = new Canvas(newIconBitmap);
        Rect srcRect = new Rect(0, 0, bgBitmap.getWidth(), bgBitmap.getHeight());
        //这里居中
        canvasIcon.translate(srcRect.centerX() - icon.getWidth() / 2,srcRect.centerY() - icon.getHeight() / 2);
        canvasIcon.drawBitmap(icon,0,0,null);
        //icon shader
        BitmapShader iconBitmapShader= new BitmapShader(newIconBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        //我们主要是了解这个
        ComposeShader composeShader = new ComposeShader(bgBitmapShader, iconBitmapShader, modes[mCurIndex]);
        paint.setShader(composeShader);
        //画个圆
        canvas.drawCircle(300,300,300,paint);
    }

    //切换模式
    public String change(){
        mCurIndex++;
        if (mCurIndex >= modes.length){
            mCurIndex = 0;
        }
        invalidate();
        return modes[mCurIndex].name();
    }
}

你可能感兴趣的:(Android,View篇)