Android Bitmap 增加水印

  /**
     * 设置水印图片在左上角
     *
     * @param src
     * @param watermark
     * @param paddingLeft
     * @param paddingTop
     * @return
     */
    public static Bitmap createWaterMaskLeftTop(Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) {
        return createWaterMaskBitmap(src, watermark, dp2px(paddingLeft), dp2px(paddingTop));
    }



 /**
     * 设置水印图片在右下角
     *
     * @param src
     * @param watermark
     * @param paddingRight
     * @param paddingBottom
     * @return
     */
    public static Bitmap createWaterMaskRightBottom(Bitmap src, Bitmap watermark, int paddingRight, int paddingBottom) {

        if (src == null) {
            return null;
        }
        if (watermark==null){
            return null;
        }

        int width = src.getWidth();
        int height = src.getHeight();

        int screenWidth = ScreenUtils.getScreenWidth(PictureApplication.getInstance());

        float scale = width * 1f / screenWidth * 1f;
        if (scale > 1f) {
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
            Bitmap bitmap = Bitmap.createBitmap(watermark, 0, 0, watermark.getWidth(), watermark.getHeight(), matrix, true);
            if (BitmapHelper.isNotEmpty(watermark)&&BitmapHelper.isNotEmpty(bitmap)&&bitmap!=watermark){
                BitmapHelper.recycler(watermark);
            }

            return createWaterMaskBitmap(src, bitmap, src.getWidth() - bitmap.getWidth() - dp2px(paddingRight), src.getHeight() - bitmap.getHeight() - dp2px(paddingBottom));
        }

        return createWaterMaskBitmap(src, watermark, src.getWidth() - watermark.getWidth() - dp2px(paddingRight), src.getHeight() - watermark.getHeight() - dp2px(paddingBottom));
    }



  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 newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图

        //创建一个bitmap
        //将该图片作为画布
        Canvas canvas = new Canvas(newb);
        //在画布 0,0坐标上开始绘制原始图片
        canvas.drawBitmap(src, 0, 0, null);
        //在画布上绘制水印图片
        canvas.drawBitmap(watermark, paddingLeft, paddingTop, null);
        // 保存
        canvas.save();
        // 存储
        canvas.restore();
        return newb;
    }



    /**
     * dp转pix
     *
     * @param dp
     * @return
     */
    public static int dp2px(float dp) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

你可能感兴趣的:(android,java,apache)