给页面添加水印,覆盖于整个页面之上,不影响页面操作
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
public class WaterMarkComponment extends Component implements Component.DrawTask{
Paint mPaint;
private String logo;
private Context context;
public WaterMarkComponment(Context context, String logo) {
super(context);
this.logo = logo;
this.context=context;
addDrawTask(this::onDraw);
}
@Override
public void onDraw(Component component, Canvas canvas) {
Display display= DisplayManager.getInstance().getDefaultDisplay(context).get();
DisplayAttributes displayAttribute = display. getAttributes();
int width = displayAttribute.width;
int height = displayAttribute.height;
mPaint=new Paint();
mPaint.setColor(Color.LTGRAY);
mPaint.setAlpha(0.2f);
mPaint.setAntiAlias(true);
mPaint.setTextSize(60);
canvas.save();
canvas.rotate(-30);
float textWidth = mPaint.measureText(logo);
int index = 0;
for (int positionY = height / 10; positionY <= height; positionY += height / 10) {
float fromX = -width + (index++ % 2) * textWidth;
for (float positionX = fromX; positionX < width; positionX += textWidth * 2) {
canvas.drawText(mPaint,logo,positionX,positionY);
}
}
canvas.restore();
}
}
/**
* 获取页面根布局
* @param component 随便传入页面中的一个控件
* @return
*/
public static ComponentContainer getDecorView(Component component) {
if (component != null) {
ComponentParent componentParent = component.getComponentParent();
if (componentParent == null) {
return (ComponentContainer) component;
} else {
return getDecorView((Component) componentParent);
}
} else {
return null;
}
}
使用方式:
ComponentContainer componentContainer= getDecorView(tf_newpwd);
componentContainer.addComponent(new WaterMarkComponment(this,"这是一个水印"));