android - Android 中给定 View 下 View 的 PorterDuff 颜色效果

标签 android porter-duff colorfilter

是否有可能在 android 中设置一个 View ,将一些颜色过滤器应用于其边界内可见的下方所有内容?就像在这个例子中:

filtering view

只是一个简单的矩形 View ,可以反转其下方所有内容的颜色。当然,当用户滚动列表时,它也会反射(reflect)在倒置框中。有没有一些简单的方法可以使用滤色器、PorterDuff 模式等来做到这一点?

最佳答案

您正在尝试使用这样的 View 层次结构来解决此问题:

  • 父级
    • ListView
    • InverterView

问题是,在这个位置,InverterView 无法控制 ListView 的绘制方式。但是您知道谁可以控制 ListView 的绘制方式吗? ListView 的父布局可以。换句话说,您真正想要的是这样的层次结构:

  • 父级
    • InverterLayout
      • ListView

现在InverterLayout负责绘制ListView,并可以对其应用效果。

class InverterLayout extends FrameLayout
{
    // structure to hold our color filter
    private Paint paint = new Paint();
    // the color filter itself
    private ColorFilter cf;
    // the rectangle we want to invert
    private Rect inversion_rect = new Rect(100, 100, 300, 300);

    public InverterLayout(Context context)
    {
        super(context);
        // construct the inversion color matrix
        float[] mat = new float[]
        {
            -1,  0,  0, 0,  255,
             0, -1,  0, 0,  255,
             0,  0, -1, 0,  255,
             0,  0,  0, 1,  0
        };
        cf = new ColorMatrixColorFilter(new ColorMatrix(mat));
    }

    @Override protected void dispatchDraw(Canvas c)
    {
        // create a temporary bitmap to draw the child views
        Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
        Canvas cc = new Canvas(b);
        // draw them to that temporary bitmap
        super.dispatchDraw(cc);
        // copy the temporary bitmap to screen without the inversion filter
        paint.setColorFilter(null);
        c.drawBitmap(b, 0, 0, paint);
        // copy the inverted rectangle
        paint.setColorFilter(cf);
        c.drawBitmap(b, inversion_rect, inversion_rect, paint);
    }
}

使用它时,确保您的 subview 有自己的背景。如果 View 是透明的并且窗口背景显示出来,则该窗口背景不会反转,因为 InverterLayout 无法控制窗口的绘制方式。

关于android - Android 中给定 View 下 View 的 PorterDuff 颜色效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419155/

相关文章:

android - 通过 Android Management API 自托管/EMM 托管私有(private)应用程序

Android - 如何定义可配置的大小形状

android - ffmpeg 在 c++ 中将 AV_SAMPLE_FMT_S16 转换为 AV_SAMPLE_FMT_FLTP

android - 将两个图像与乘法和 % 不透明度混合在一起

java - webservice...无法解析为类型

Android:圆形可绘制对象

android - PorterDuff.Mode 在 android graphics 中是什么意思。它有什么作用?

java - ColorFilter 仅特定颜色

android - 以编程方式更改图像的颜色Android