Android 有关图片水印设计的实现

例如:拍摄时间+地点 文字水印与图片水印

思路如下:

1.获取要添加水印图片宽高

Bitmap bitmap = BitmapFactory.decodeFile(new File(resources).getAbsolutePath());
// 获取图片的宽高
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();

2.获取水印图片

//获取水印图片
Bitmap waterImage = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_release_bg);

3.获取缩放图片

public static Bitmap getNewBitmap(Bitmap bitmap, int newWidth, int newHeight) {
    // 获得图片的宽高.
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    // 计算缩放比例.
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // 取得想要缩放的matrix参数.
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    // 得到新的图片.
    Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    return newBitmap;
}

4.绘制图片到画布

Bitmap newBitmap = getNewBitmap(waterImage, bitmapWidth, bitmapHeight);
Canvas canvas = new Canvas(bmp);
// 画背景图
canvas.drawBitmap(bitmap, 0, 0, null);
//在画布上绘制水印图片
canvas.drawBitmap(newBitmap, 0, 0, null);

5.绘制文字,准备画笔,确定绘制位置

//-------------开始绘制文字--------------
if (!TextUtils.isEmpty(watermarkText)) {
   int screenWidth = getScreenWidth();
   float textSize = dp2px(mContext, 13) * bitmapWidth / screenWidth;
   // 创建画笔
   TextPaint mPaint = new TextPaint();
   // 文字矩阵区域
   Rect textBounds = new Rect();
   // 水印的字体大小
   mPaint.setTextSize(textSize);
   // 文字阴影
   //mPaint.setShadowLayer(1f, 0f, 1f, Color.YELLOW);
   // 抗锯齿
   mPaint.setAntiAlias(true);
   // 水印的区域
   mPaint.getTextBounds(watermarkText, 0, watermarkText.length(), textBounds);
   // 水印的颜色
   mPaint.setColor(Color.WHITE);
   StaticLayout layout = new StaticLayout(watermarkText, 0, watermarkText.length(), mPaint, (int) (bitmapWidth - textSize),
           Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.5F, true);
   // 文字开始的坐标
   float textX = dp2px(mContext, 8) * bitmapWidth / screenWidth;
   float textY = bitmapHeight - dp2px(mContext, 40) * bitmapHeight / screenWidth;
   // 画文字
   canvas.translate(textX, textY);
   layout.draw(canvas);
}
//保存所有元素
canvas.save();
canvas.restore();

总结:至此,一个小的水印就绘制在了新的Bitmap上.我们根据新的Bitmap可以写在本地,上传服务器.

posted @ 2020-07-09 09:31  任小卡  阅读(513)  评论(0编辑  收藏  举报