1.生成图片背景
public class WaterMarkUtil {
private DensityUtil densityUtil;
private volatile static WaterMarkUtil mInstance = null;
public static WaterMarkUtil getInstance() {
if (mInstance == null) {
synchronized (SpUtils.class) {
if (mInstance == null) {
mInstance = new WaterMarkUtil();
}
}
}
return mInstance;
}
public void setWaterMarkTextBg(View view, Context gContext, String gText) {
view.setBackground(drawTextToBitmap(gContext, gText));
}
public BitmapDrawable drawTextToBitmap(Context gContext, String gText) {
gText = gText + " ";
Bitmap waterMarkBitmap = ACache.get(gContext).getAsBitmap(gText);
if (waterMarkBitmap != null && !waterMarkBitmap.isRecycled()) {
BitmapDrawable drawable = new BitmapDrawable(waterMarkBitmap);
drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
drawable.setDither(true);
return drawable;
}
try {
Bitmap bitmap = Bitmap.createBitmap(AppTools.dip2px(420), AppTools.dip2px(400), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(getColorPrimary(gContext));
Paint paint = new Paint();
paint.setColor(Color.LTGRAY);
paint.setAlpha(80);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(AppTools.dip2px(70));
Path path = new Path();
path.moveTo(AppTools.dip2px(0), AppTools.dip2px(300));
path.lineTo(AppTools.dip2px(210) * 2, AppTools.dip2px(0));
canvas.drawTextOnPath(gText, path, AppTools.dip2px(0), AppTools.dip2px(50), paint);
canvas.save();
canvas.restore();
ACache.get(gContext).put(gText, bitmap);
BitmapDrawable drawable = new BitmapDrawable(bitmap);
drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
drawable.setDither(true);
return drawable;
} catch (Exception e) {
}
return null;
}
public int getColorPrimary(Context context){
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
return typedValue.data;
}
}
2.代码使用
WaterMarkUtil instance = WaterMarkUtil.getInstance();
instance.setWaterMarkTextBg(relWatermark, getContext(), user.name + " " + user.telephone.substring(user.telephone.length() - 4));
3.布局使用
<RelativeLayout
android:id="@+id/rel_watermark"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="@id/header">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:overScrollMode="never"
android:paddingBottom="@dimen/home_tab_widget_height"
android:background="@color/transparent"
android:scrollbars="none" />
</RelativeLayout>