[英]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.