是否有可能在 android 中设置一个 View ,将一些颜色过滤器应用于其边界内可见的下方所有内容?就像在这个例子中:
只是一个简单的矩形 View ,可以反转其下方所有内容的颜色。当然,当用户滚动列表时,它也会反射(reflect)在倒置框中。有没有一些简单的方法可以使用滤色器、PorterDuff 模式等来做到这一点?
最佳答案
您正在尝试使用这样的 View 层次结构来解决此问题:
- 父级
- ListView
- InverterView
问题是,在这个位置,InverterView
无法控制 ListView
的绘制方式。但是您知道谁可以控制 ListView
的绘制方式吗? ListView
的父布局可以。换句话说,您真正想要的是这样的层次结构:
- 父级
- InverterLayout
- 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);
}
}
使用它时,确保您的 subview 有自己的背景。如果 View 是透明的并且窗口背景显示出来,则该窗口背景不会反转,因为 InverterLayout
无法控制窗口的绘制方式。
关于android - Android 中给定 View 下 View 的 PorterDuff 颜色效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419155/