最近项目提出新需求,要求在拍照后在图片上添加用户信息的水印,so,楼主重新整理封装了一个简单的拍照+水印的工具类,需求不同,仅供参考。文件操作及权限做了适配,支持androidN及以上版本,放心使用。
效果演示:
如何调用相机这里就不介绍了,因为小伙伴们基本都使用过,主要介绍下实现水印的方式,实现水印效果也很简单,利用paint及canvas操作bitmap在对应位置进行绘制文本即可,首先定义画笔,设置水印颜色、大小及文本:
Paint paint = newPaint(Paint.ANTI_ALIAS_FLAG);paint.setColor(color);paint.setTextSize(size);Rect bounds = newRect();paint.getTextBounds(text,0,text.length(),bounds);
定义好画笔后新建canvas对bitmap进行绘制,这里应该注意的是在Android代码里是不允许直接修改Bitmap资源文件,如果不copy一份的话会抛异常
Caused by: java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor
绘制代码如下:
Bitmap.Config bitmapConfig = bitmap.getConfig();paint.setDither(true);// 获取跟清晰的图像采样paint.setFilterBitmap(true);// 过滤一些if(bitmapConfig == null) {
bitmapConfig = Bitmap.Config.ARGB_8888;}
bitmap = bitmap.copy(bitmapConfig, true);Canvas canvas = newCanvas(bitmap);canvas.drawText(text,paddingLeft,paddingTop,paint);
我们看下drawText的源码
/*** Draw the text, with origin at (x,y), using the specified paint. The* origin is interpreted based on the Align setting in the paint.**@paramtextThe text to be drawn*@paramxThe x-coordi