[英]Invert paint color based on background
我正在编写一个自定义进度栏。 我想创建类似的效果
其中“ 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
绘画以根据其在“画布”上绘制的内容来更改颜色?
即使问题很老,我也希望分享解决方案。
您不能使用“反转” 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.