Android中的PorterDuff颜色效果,用于给定视图下的视图

Łuk*_*mek 13 android colorfilter porter-duff

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

过滤视图

只是一个简单的矩形视图,可以反转其下方所有内容的颜色.当然,当用户滚动列表时,它也会反映在倒置框中.有没有一些简单的方法来使用彩色滤镜,PorterDuff模式等?

j__*_*__m 14

您正尝试使用如下视图层次结构来解决此问题:

    • 列表显示
    • InverterView

问题是,在这个位置,InverterView无法控制如何ListView绘制.但是你知道谁能控制如何ListView绘制? ListView的父布局确实如此.换句话说,你真正想要的是这样的层次结构:

    • InverterLayout
      • 列表显示

现在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此功能时,请确保您的子视图具有自己的背景.如果视图是透明的并且窗口背景显示,那么窗口背景将不会被反转,因为InverterLayout它无法控制窗口的绘制方式.