android - 根据背景反转油漆颜色

标签 android

我正在写一个自定义进度条。我想创建一个类似于

的效果

enter image description here

其中“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 绘制以根据“ Canvas 上”下方绘制的内容更改颜色?

最佳答案

即使这个问题很老,我也想分享解决方案。

您不能使用“反转”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();

关于android - 根据背景反转油漆颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943091/

相关文章:

android - 是什么导致了ANR?

android - 日志: "Skipped 33 frames"

java - 在 Android 上回收膨胀 View

java - 将另一个 Activity 的数据显示到另一个 Activity 。动态地从类到数组列表到线性布局

Android Tab 布局,接受的模式?

android - java.util.NoSuchElementException : List contains no element matching the predicate

android - 如何以及什么将 Java 字节码转换为 Android dex 文件?

android - 升级后 android Lollipop 设备上的权限问题

android - 如何在开发过程中测试 Firebase 推送通知而不将应用程序发布到 Playstore?

android - Android Studio和TDD-如何在几秒钟内运行测试