2014-04-08 16 views
5

Piszę niestandardowy pasek postępu. Chciałbym utworzyć efekt podobny doOdwrócony kolor farby na podstawie tła

enter image description here

gdzie zmiany „50%” kolor biały tekst dynamicznie podczas gdy czarny pasek postępuje słusznie. Czy jest to możliwe przy użyciu "prostych" rozwiązań? Sprawdziłem PorterDuff, ColorFilters, xFermodes, nic nie działa. Jakieś pomysły? ATM mój kod wygląda czegoś takiego:

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

Czy istnieje sposób zmodyfikować pBlackTxtM farby do zmiany koloru na podstawie co jest sporządzony pod nim „na płótnie”?

Odpowiedz

3

Nawet jeśli pytanie jest dość stare, chciałbym podzielić się z tym rozwiązaniem.

Nie można tego zrobić przy użyciu "odwracania" Paint, ale można to osiągnąć za pomocą przycinania.

Chodzi o to, aby narysować tekst dwukrotnie, raz w kolorze czarnym i raz w kolorze białym, jednocześnie ustawiając region wycinania tak, aby pasował do odpowiedniej części paska.

Oto kod, aby przedstawić ideę:

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