<异空间>项目技术分享系列——扩展函数为Bitmap添加文字水印canvas
对图片Bitmap绘制文字水印仍是比较常见的需求,毕竟版权意识都在加强(用户能够给本身图片加上用户名),还能够为用户提供更多的信息(例如视频缩略图)网络
先上效果图(比较简单的效果,可继续扩展实现),如下代码使用Kotlin语言编写ide
首先注意不能对进行拉伸或缩放前的Bitmap进行绘制水印,不然水印也会一块儿被拉伸缩放函数
应该提早将Bimap拉伸,再进行绘制操做字体
示例代码:this
//将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)code
下面示例代码目前只实现了在右下角绘制,可继续扩展:视频
/** * 给一张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做为设置图片的来源,不然的话,会致使图片填充方式设置无效的状况。blog
但愿对有须要的人有帮助~😊图片