美文网首页
android图片加水印

android图片加水印

作者: starCoder | 来源:发表于2017-04-14 17:35 被阅读470次
    public static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark) {
            int paddingTop ;
            if (src == null) {
                return null;
            }
            //获取图片宽高
            int width = src.getWidth();
            int height = src.getHeight();
            //获取水印图片宽高
            int watermarkWidth = watermark.getWidth();
            int watermarkHeight = watermark.getHeight();
            //缩小或者放大水印图片  使水印宽度与图片一致
            if (width > 0 && watermarkWidth > 0) {
                float scale = ((float) width) / watermarkWidth;
                // 取得想要缩放的matrix参数
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                // 得到新的水印图片
                watermark = Bitmap.createBitmap(watermark, 0, 0, watermarkWidth, watermarkHeight, matrix, true);
                watermarkHeight = watermark.getHeight();
            }
            if (height > watermarkHeight) {
                //设置水印图片竖直位置在图片中间
                paddingTop = (height - watermarkHeight) / 2;
            } else {
                paddingTop = 0;
            }
            //创建一个bitmap
            Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
            //将该图片作为画布
            Canvas canvas = new Canvas(newBitmap);
            //在画布 0,0坐标上开始绘制原始图片
            canvas.drawBitmap(src, 0, 0, null);
            // 建立Paint 物件
            Paint vPaint = new Paint();
            vPaint.setStyle(Paint.Style.STROKE);   //空心
            vPaint.setAlpha(80);
            //在画布上绘制水印图片
            canvas.drawBitmap(watermark, 0, paddingTop, vPaint);
            // 保存
            canvas.save(Canvas.ALL_SAVE_FLAG);
            // 存储
            canvas.restore();
            return newBitmap;
        }
    

    相关文章

      网友评论

          本文标题:android图片加水印

          本文链接:https://www.haomeiwen.com/subject/mpqgattx.html