我正在编写自定义进度条。我想创建一个类似于
的效果
其中" 50%"当黑条向右前进时,文本颜色动态变为白色。是否可以使用"简单"解决方案?我查了一下PorterDuff,ColorFilters,xFermodes,似乎没什么用。有任何想法吗? ATM我的代码看起来像这样:
Rect r = new Rect(1, 1, m_width-1, m_height-1);
canvas.drawRect(r, pWhiteFill);
r = new Rect(1, 1, progressWidth, m_height-1);
canvas.drawRect(r, pBlackFill);
canvas.drawText(String.valueOf(progress)+"%", m_width/2, m_height/2, pBlackTxtM);
是否有办法修改pBlackTxtM
绘画以根据在画布下方绘制的内容来更改颜色'?
答案 0 :(得分:3)
即使问题很老,我也想与大家分享解决方案。
你不能使用"反转" Paint
,但您可以使用剪辑来实现它。
这个想法是两次绘制文本,一次是黑色,一次是白色,同时设置剪裁区域以匹配条的各个部分。
以下是一些概述这个想法的代码:
// store the state of the canvas, so we can restore any previous clipping
canvas.save();
// note that it's a bad idea to create the Rect during the drawing operation, better do that only once in advance
// also note that it might be sufficient and faster to draw only the white part of the bar
Rect r = new Rect(1, 1, m_width-1, m_height-1);
canvas.drawRect(r, pWhiteFill);
// this Rect should be created when the progress is set, not on every drawing operation
Rect r_black = new Rect(1, 1, progressWidth, m_height-1);
canvas.drawRect(r_black, pBlackFill);
// set the clipping region to the black part of the bar and draw the text using white ink
String text = String.valueOf(progress)+"%";
canvas.cliprect(r_black);
canvas.drawText(text, m_width/2, m_height/2, pWhiteTxtM);
// draw the same text again using black ink, setting the clipping region to the complementary part of the bar
canvas.clipRect(r, Region.Op.XOR);
canvas.drawText(text, m_width/2, m_height/2, pBlackTxtM);
canvas.restore();