我试图达到一个类似的效果:
android - 使用蒙版显示带有2种不同颜色的TextView-LMLPHP
我现在做的是:

public MaskedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    p = new Paint(Paint.ANTI_ALIAS_FLAG);
    p.setTextSize(25);
    p.setColor(Color.GREEN);

    pReplace = new Paint(p);
    pReplace.setColor(Color.BLUE);
    pReplace.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));

    pMask = new Paint();
    int lightGradientColor = getResources().getColor(R.color.dailyGoalLowLight);
    int darkGradientColor = getResources().getColor(R.color.dailyGoalLowDark);
    Shader shader = new LinearGradient(0, 0, 150, 0, lightGradientColor, darkGradientColor, Shader.TileMode.CLAMP);
    pMask.setShader(shader);
    pMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    if (!Utils.isEmpty(sText)) {
        canvas.drawText(sText, 150, getHeight() / 2, p);
        canvas.drawRect(0, 0, 180, getHeight(), pMask);
        canvas.drawText(sText, 150, getHeight()/2, pReplace);
    }
    canvas.restore();
}

这将导致:
android - 使用蒙版显示带有2种不同颜色的TextView-LMLPHP
关闭,这里的问题是设置pMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));时水平线性渐变不显示。
如果我把那一行注释掉,会得到以下结果:
android - 使用蒙版显示带有2种不同颜色的TextView-LMLPHP
再次关闭,但现在线性渐变完全覆盖文本。有人能帮我解决我在这里丢失的东西吗?有没有更好的方法来达到这个效果?

最佳答案

PorterDuff.Mode.SRC_IN也许会有帮助。
应该调用setLayerType(View.LAYER_TYPE_SOFTWARE, null);来使用SRC_IN

public class MaskedTextView extends View {

    private final Paint pLeftBg;
    private final Paint pText;
    private final Paint pRightMask;
    private String mText = "web";

    public MaskedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        pLeftBg = new Paint();
        int lightGradientColor = ContextCompat.getColor(getContext(), R.color.dailyGoalLowLight);
        int darkGradientColor = ContextCompat.getColor(getContext(), R.color.dailyGoalLowDark);
        Shader shader = new LinearGradient(0, 0, 150, 0, lightGradientColor, darkGradientColor, Shader.TileMode.CLAMP);
        pLeftBg.setShader(shader);

        pText = new Paint(Paint.ANTI_ALIAS_FLAG);
        pText.setTextSize(50);
        pText.setColor(Color.WHITE);

        pRightMask = new Paint();
        pRightMask.setColor(ContextCompat.getColor(getContext(), R.color.dailyGoalLowLight));
        pRightMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        canvas.drawRect(0, 0, 100, getHeight(), pLeftBg);
        canvas.drawText(mText, 50, getHeight() / 2, pText);
        canvas.drawRect(100, 0, getWidth(), getHeight(), pRightMask);
        canvas.restore();
    }
}

输出:
android - 使用蒙版显示带有2种不同颜色的TextView-LMLPHP

08-17 16:44