2014-04-08 12 views
5

Ich schreibe eine benutzerdefinierte Fortschrittsbalken. Ich möchte ähnliche Wirkung schaffen, umFarbe umkehren basierend auf Hintergrund

enter image description here

, wo die „50%“ Textfarbe ändert sich dynamisch auf weiß, während der schwarze Balken rechts fortschreitet. Ist das mit "einfachen" Lösungen möglich? Ich habe PorterDuff, ColorFilters, xFermodes nachgeschlagen, nichts scheint zu funktionieren. Irgendwelche Ideen? ATM mein Code sieht etw wie folgt aus:

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

Gibt es eine Möglichkeit pBlackTxtM Farbe zu ändern, Farbe zu ändern, basierend auf was unten ist es auf der Leinwand 'gezogen?

Antwort

3

Auch wenn die Frage ziemlich alt ist, möchte ich die Lösung dazu teilen.

Sie können dies nicht mit einem "invertierenden" Paint tun, aber Sie können es mit Clipping erreichen.

Die Idee besteht darin, den Text zweimal zu zeichnen, einmal in schwarz und einmal in weißer Farbe, während der Ausschnittbereich auf den jeweiligen Teil des Balkens eingestellt wird.

Hier ist ein Code, die Idee zu skizzieren:

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