7

我正在尝试实现与此类似的效果:

在此处输入图像描述

我现在在做什么:

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();
}

这导致:

在此处输入图像描述

关闭,这里的问题是设置pMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));.

如果我注释掉该行,我会得到以下结果:

在此处输入图像描述

再次关闭,但现在线性渐变完全覆盖了文本。有人可以帮我解决我在这里缺少的东西。有没有更好的方法来达到这个效果?

4

1 回答 1

6

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();
    }
}

输出:

在此处输入图像描述

于 2016-10-04T09:20:36.860 回答