Android添加浮水印的正確方法 只要三步!_Android

來源:互聯網
上載者:User

開門見山,添加浮水印的方法非常簡單,其實就只有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

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.