開門見山,添加水印的方法非常簡單,其實就只有3個步驟:
1、載入原始圖片
2、載入水印圖片
3、保存帶有水印的圖片
實現的原理就是:獲取原始圖片的寬高,然后,新建一個同樣寬高的bitmap,將這個新的bitmap作為畫布,接著,就在這個畫布上面畫原圖,畫水印圖片,有文字就接著畫文字。
上面哪個順序一定不能亂,不然你可能就看不到水印,或則文字了,因為畫在原圖下面去了
繪制水印的代碼如下:
private static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) { if (src == null) { return null; } int width = src.getWidth(); int height = src.getHeight(); //創建一個bitmap Bitmap newBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);// 創建一個新的和SRC長度寬度一樣的位圖 //將該圖片作為畫布 Canvas canvas = new Canvas(newBitmap); //在畫布 0,0坐標上開始繪制原始圖片 canvas.drawBitmap(src, 0, 0, null); //在畫布上繪制水印圖片 canvas.drawBitmap(watermark, paddingLeft, paddingTop, null); // 保存 canvas.save(Canvas.ALL_SAVE_FLAG); // 存儲 canvas.restore(); return newBitmap; }繪制文字的代碼如下:
/** * 繪制文字到中間 * * @param context * @param bitmap * @param text * @param size * @param color * @return */ public static Bitmap drawTextToCenter(Context context, Bitmap bitmap, String text, int size, int color) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(color); paint.setTextSize(dp2px(context, size)); Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); return drawTextToBitmap(context, bitmap, text, paint, bounds, (bitmap.getWidth() - bounds.width()) / 2, (bitmap.getHeight() + bounds.height()) / 2); } /** * 圖片上繪制文字 */ private static Bitmap drawTextToBitmap(Context context, Bitmap bitmap, String text, Paint paint, Rect bounds, int paddingLeft, int paddingTop) { Config bitmapConfig = bitmap.getConfig(); paint.setDither(true); // 獲取跟清晰的圖像采樣 paint.setFilterBitmap(true);// 過濾一些 if (bitmapConfig == null) { bitmapConfig = Config.ARGB_8888; } bitmap = bitmap.copy(bitmapConfig, true); Canvas canvas = new Canvas(bitmap); canvas.drawText(text, paddingLeft, paddingTop, paint); return bitmap; }效果圖如下:

github地址為:https://github.com/chenguo4930/Watermark
git地址為:https://github.com/chenguo4930/Watermark.git
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答