本文共 2339 字,大约阅读时间需要 7 分钟。
<异空间>项目技术分享系列——扩展函数为Bitmap添加文字水印
对图片Bitmap绘制文字水印还是比较常见的需求,毕竟版权意识都在增强(用户可以给自己图片加上用户名),还可以为用户提供更多的信息(例如视频缩略图)
先上效果图(比较简单的效果,可继续扩展实现),以下代码使用Kotlin语言编写
首先注意不能对进行拉伸或缩放前的Bitmap进行绘制水印,否则水印也会一起被拉伸缩放
应该提前将Bimap拉伸,再进行绘制操作
示例代码:
//将Bitmap进行缩放,获得缩放完成后的Bitmap后,再绘制文字水印bitmap?.let {thumb -> bitmap = Bitmap.createScaledBitmap( //缩放 thumb , ConvertUtils.dp2px(140F), ConvertUtils.dp2px(100F),false ) .addTextWatermark(length , ConvertUtils.dp2px(16F) , Color.WHITE ,0F,0F,false)}
addTextWatermark
方法是对Bitmap类的一个扩展方法(Kotlin)
下面示例代码目前只实现了在右下角绘制,可继续扩展:
/** * 给一张Bitmap添加水印文字。 * * @param content 水印文本 * @param textSize 水印字体大小 ,单位pix。 * @param color 水印字体颜色。 * @param x 起始坐标x * @param y 起始坐标y * @param recycle 是否回收 * @return 已经添加水印后的Bitmap */ fun Bitmap.addTextWatermark( content: String?,//文字内容 textSize: Int, //文字大小 color: Int, //文字颜色 x: Float, //x,y暂时比较难用,因为要指定具体位置,难以在外部直接测量文字的坐标 y: Float, recycle: Boolean //Bitmap内存是否回收 ): Bitmap? { if ( content == null) return null val ret = this.copy(this.config, true) val paint = Paint(Paint.ANTI_ALIAS_FLAG) val canvas = Canvas(ret) paint.color = color paint.textSize = textSize.toFloat() //绘制文字 val bounds = Rect() paint.getTextBounds(content, 0, content.length, bounds) //默认在 Bitmap的 右下角位置开始绘制文字 canvas.drawText(content, this.width.toFloat()-bounds.width() - 20F , this.height.toFloat() - bounds.height() + 20F, paint) if (recycle && !this.isRecycled) this.recycle() return ret }
设置ImageView填充方式的前提是使用src作为设置图片的来源,否则的话,会导致图片填充方式设置无效的情况。
希望对有需要的人有帮助~😊
转载地址:http://uymzz.baihongyu.com/