harmony--页面水印控件

本文介绍如何在Android应用中使用OHOS框架创建一个可覆盖整个页面的水印组件,该组件在不影响页面操作的同时,显示预设的Logo。通过WaterMarkComponment类的实例化和自定义绘制方法,实现了动态添加水印的功能。
摘要由CSDN通过智能技术生成

给页面添加水印,覆盖于整个页面之上,不影响页面操作

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,"这是一个水印"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值