Android给图片添加带半透明背景的水印:
关键点:将TextView转换成bitmap,将水印bitmap绘制在原图上。
水印样式文件:layout_water_mark.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv_mark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#60000000"
android:paddingHorizontal="12dp"
android:paddingVertical="7dp"
android:text="@string/app_name"
android:textColor="@color/white"
android:textSize="12sp" />
工具类:PictureUtil.java
package com.kedacom.convenientshoot.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;
import android.widget.TextView;
public class PictureUtil {
/**
* 图片加水印
*
* @param src
* @param mark1
* @param mark2
* @param paddingLeft
* @param paddingTop
* @return
*/
public static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap mark1, Bitmap mark2, int paddingLeft, int paddingTop) {
if (src == null) {
return null;
}
int width = src.getWidth();
int height = src.getHeight();
//创建一个bitmap
Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
//将该图片作为画布
Canvas canvas = new Canvas(newb);
//在画布 0,0坐标上开始绘制原始图片
canvas.drawBitmap(src, 0, 0, null);
//在画布上绘制水印图片
canvas.drawBitmap(mark1, paddingLeft, paddingTop, null);//左上方
canvas.drawBitmap(mark2, paddingLeft, src.getHeight() - mark2.getHeight(), null);//左下方
// 保存
canvas.save();
// 存储
canvas.restore();
return newb;
}
/**
* TextView 转换成Bitmap
* @param tv
* @return
*/
public static Bitmap buildTextViewBitmap(TextView tv) {
tv.setDrawingCacheEnabled(true);
tv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(tv.getDrawingCache());
tv.destroyDrawingCache();
return bitmap;
}
}
方法调用:
private Bitmap getWatermarkBitmap(String compressFile) {
LayoutInflater inflater = LayoutInflater.from(AppUtil.getApp());
TextView tv1 = (TextView) inflater.inflate(R.layout.layout_water_mark, null);
TextView tv2 = (TextView) inflater.inflate(R.layout.layout_water_mark, null);
Bitmap src = BitmapFactory.decodeFile(compressFile);//原图
tv1.setText("2022.03.10 09:00:00");//时间
tv1.setWidth(src.getWidth());//水印和图片宽度一致
tv2.setText("河北省安阳市金山屯区宝山路32号真新六街坊");//地点
tv2.setWidth(src.getWidth());
Bitmap watermarkBitmap = PictureUtil.createWaterMaskBitmap(src, PictureUtil.buildTextViewBitmap(tv1), PictureUtil.buildTextViewBitmap(tv2), 0, 0);//水印图片
return watermarkBitmap;
}
android 给图片添加文字(换行)水印 (普通水印)