我想实现这样的目标:
首先想到的是在画布上绘制两次文本,并用形状覆盖第一个文本。但也许有更好的解决办法。
最佳答案
一种方法是使用PorterDuffXfermode
在文本上合成蓝色矩形。您可以在绘制文本之后扩展TextView
并覆盖onDraw()
来绘制矩形,并且使用适当的模式(我相信XOR
是您想要的模式)应该可以达到所需的效果。像这样的:
public class ProgressTextView extends TextView {
private static final float MAX_PROGRESS = ...;
private Paint mPaint;
public ProgressTextView(Context context) {
super(context);
initPaint();
}
/* other constructor omitted, but do the same pattern in those */
private void initPaint() {
mPaint = new Paint();
mPaint.setColor(...);
mPaint.setXfermode(new PorterDuffXfermode(Mode.XOR));
// note: you may also need the following line if hardware accel is available
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawProgress(canvas);
}
private void drawProgress(Canvas canvas) {
int w = getWidth() - getPaddingLeft() - getPaddingRight();
int h = getHeight() - getPaddingTop() - getPaddingBottom();
float progress = getProgress();
float rectW = w * (progress / MAX_PROGRESS);
int saveCount = canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
canvas.drawRect(0, 0, rectW, h, mPaint);
canvas.restoreToCount(saveCount);
}
private float getProgress() {
// TODO
}
}
关于波特/达夫合成的更多信息:http://ssp.impulsetrain.com/porterduff.html