Android 水印效果
本文主要介绍下android 中水印的实现效果.
实现的方式有多种,就不一一赘述了, 本文就是通过自定义drawable来实现水印.
不多说,直接上代码吧:
java
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
public class WatermarkDrawable extends Drawable {
private String watermarkText;
private Paint paint;
private boolean isOne;
private int numX, numY;
private int mWidth, mHeight, mOffSet, textWidth, textHeight;
private Context mContext;
public WatermarkDrawable(Context context, String text, boolean isOne) {
watermarkText = text;
mContext = context;
this.isOne = isOne;
paint = new Paint();
paint.setColor(Color.GRAY);
paint.setTextSize(50);
paint.setAlpha(100);
textWidth = (int) paint.measureText(watermarkText);
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
textHeight = (int) (fontMetrics.descent - fontMetrics.ascent);
Resources resources = mContext.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
mWidth = dm.widthPixels;
mHeight = dm.heightPixels;
mOffSet = ((mHeight - mWidth) >> 1);
int max = Math.max(mWidth, mHeight);
numX = max / (textWidth + 50) + 2;
numY = max / (textHeight + 100) + 2;
}
@Override
public void draw(Canvas canvas) {
if (isOne) {
drawOneWaterMark(canvas);
} else {
drawFullWaterMark(canvas);
}
}
private void drawOneWaterMark(Canvas canvas) {
int width = getBounds().width();
int height = getBounds().height();
float textWidth = paint.measureText(watermarkText);
float x = (width - textWidth) / 2;
float y = height / 2;
canvas.drawText(watermarkText, x, y, paint);
}
private void drawFullWaterMark(Canvas canvas) {
for (int i = 0; i < numY; i++) {
int yy = (100 >> 1) + (100 + textHeight) * i;
for (int j = 0; j < numX; j++) {
float xx = (i % 2) * (50 + textWidth) / 2 + j * (50 + textWidth);
canvas.drawText(watermarkText, xx, yy, paint);
}
}
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
这里只是简单实现下单个水印以及全局多个水印的效果, 后续水印的效果:如 旋转角度,水印的多少,水印文案的限制在继续优化吧.
设置水印的方式也很简单:
java
WatermarkDrawable watermarkDrawable = new WatermarkDrawable(this,"测试", false);
获取acitvity的根布局, 设置背景drawable即可.
我们可以通过调用setForeground方法, 让水印在整个页面的前台,从而不被页面中的组件遮挡.
效果如下: