View 蒙层效果实现 - litonghui/TechBlog GitHub Wiki

图片的底层或者四周设置蒙层效果,通常使用的是Shape方法,Xml布局文件 Shader 子类BitmapShader,LinearGradient,RadialGradient,SweepGradient,ComposeShader组合渲染直接代码实现。

Xml布局文件

FragmentLayout 中设置ImageView 和 普通View, 对普通View 设置一个蒙层背景由底部深色,渐变到透明覆盖在ImageView ,实现蒙层效果。代码如下:
<?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="150dp">
  <ImageView
    android:id="@+id/img_banner"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="fitCenter"
    android:background="@mipmap/icon_temp"/>
  <View
    android:id="@+id/overlay"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/trending_gradient_shape"/>
 </FrameLayout>
对于drawable 中的 shape 设置渐变蒙层效果:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >
 <gradient android:angle="90"
    android:endColor="#00ffffff"
    android:startColor="#670032"
    android:centerColor="00ffffff"
    android:type="linear"/>
</shape>
其中增加centerColor 是避免整张图片被蒙住,上面图片还是清晰可见的。

xml 布局shape 文件可以方便实现蒙层效果,但是对于颜色可以配置的模糊效果就无法实现,通过Shader 子类实现。

Shader 子类

使用LinearGradient 对 bitmap 线性渲染。
public static Bitmap addGradient(Bitmap originalBitmap,int templateColor) {
    int width = originalBitmap.getWidth();
    int height = originalBitmap.getHeight();
    Bitmap updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(updatedBitmap);
    canvas.drawBitmap(originalBitmap, 0, 0, null);

    Paint paint = new Paint();
    LinearGradient linearGradient = new LinearGradient(0, height / 4, 0, height * 3 / 4,
            Color.TRANSPARENT, templateColor, Shader.TileMode.CLAMP);
    paint.setShader(linearGradient);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
    canvas.drawRect(0, 0, width, height, paint);
    return updatedBitmap;
}
⚠️ **GitHub.com Fallback** ⚠️