Android原生绘图(十三):ComposeShader,PorterDuff.mode及Xfermode

1,551 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。

1. ComposeShader 简介

ComposeShader 组合另外两种shader的效果。
ComposeShader构造函数:

/**
 * Create a new compose shader, given shaders A, B, and a combining mode.
 * When the mode is applied, it will be given the result from shader A as its
 * "dst", and the result from shader B as its "src".
 *
 * @param shaderA  The colors from this shader are seen as the "dst" by the mode
 * @param shaderB  The colors from this shader are seen as the "src" by the mode
 * @param mode     The mode that combines the colors from the two shaders. If mode
 *                 is null, then SRC_OVER is assumed.
*/
public ComposeShader(@NonNull Shader shaderA, @NonNull Shader shaderB, @NonNull Xfermode mode) ;
/**
 * Create a new compose shader, given shaders A, B, and a combining PorterDuff mode.
 * When the mode is applied, it will be given the result from shader A as its
 * "dst", and the result from shader B as its "src".
 *
 * @param shaderA  The colors from this shader are seen as the "dst" by the mode
 * @param shaderB  The colors from this shader are seen as the "src" by the mode
 * @param mode     The PorterDuff mode that combines the colors from the two shaders.
*/
public ComposeShader(@NonNull Shader shaderA, @NonNull Shader shaderB,
        @NonNull PorterDuff.Mode mode) ;

参数说明:
shaderA,shaderB:要混合的两种shader,
Xfermode mode: 组合两种shader颜色的模式,
PorterDuff.Mode mode: 组合两种shader颜色的模式。

2.Xfermode是什么呢?

Xfermode称为图形混合模式也被称为过渡模式,把两个图形混合成一张图。

PorterDuffXfermode用于图形合成时的图像过渡模式计算。

构造函数:
PorterDuffXfermode(PorterDuff.Mode mode)
mode:混合图像模式。

3.什么是PorterDuff.Mode?

PorterDuff.Mode分为Alpha合成模式和混合模式。图像合成就是将源像素和背景像素的颜色进行混合,最终显示的颜色取决于其RGB颜色分量和Alpha值。

Android 中PorterDuff.Mode模式包括:

  • Mode.CLEAR;
  • Mode.SRC;
  • Mode.DST;
  • Mode.SRC_OVER;
  • Mode.DST_OVER;
  • Mode.SRC_IN;
  • Mode.DST_IN;
  • Mode.SRC_OUT;
  • Mode.DST_OUT;
  • Mode.SRC_ATOP;
  • Mode.DST_ATOP;
  • Mode.XOR;
  • Mode.DARKEN;
  • Mode.LIGHTEN;
  • Mode.MULTIPLY;
  • Mode.SCREEN;
  • Mode.ADD;
  • Mode.OVERLAY;

4. paint.setXfermode

RectF rectF = new RectF(0, 0, 700, 700);
canvas.saveLayer(rectF,mPaint);
canvas.drawBitmap(dstBmp, 0, 0, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.OVERLAY));
canvas.drawBitmap(srcBmp, 0, 0, mPaint);
mPaint.setXfermode(null);
canvas.restore();

5.ComposeShader

混合两种shader,shader可以是BitmapShader,LinearGradient,RadialGradient,SweepGradient,所以可以有很多种组合。由于最后一个参数跟PorterDuff.mode有关,所以mode应用时将把从shaderA(ComposeShader 第一个参数)中获取的结果作为目标图像,shaderB(ComposeShader第二个参数)中获取的结果作为源图像,进行混合叠加。如果相交的两个图像大小不同,就会存在不想交的部分,不想交的部分是不会相互影响的