图片上增加水印文字
适用场景:在图片上增加文字水印,如图:
实现思路:在画布上画两张Bitmap,底部一张用来展示需要添加文字水印的图片,顶部一张透明的用来展示水印文字
实现代码:
//给ImageView设置bigmap展示
private void setImageView(){
new Thread(new Runnable() {//需要在线程中绘制
@Override
public void run() {
//获得需要添加水印文字的图片
Bitmap srcbitmap = BitmapFactory.decodeResource(WaterMarkTestActivity.this.getResources(), R.drawable.box_logo);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int srcWidth = dm.widthPixels;
int srcHeight = dm.heightPixels - 20;
Util.LOGD(TAG,"bitmap.getWidth():"+srcWidth+" , bitmap Height:"+srcHeight);
//创建屏幕大小的bitmap
final Bitmap resultBitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
//将该图作为画布
Canvas canvas = new Canvas(resultBitmap);
//在画布上绘制底部图片bitmap
canvas.drawBitmap(srcbitmap, srcWidth/3, srcHeight/3, null);
//获得顶部透明的文字bitmap
final Bitmap markBitmap = getMarkTextBitmap(srcWidth, srcHeight);
//在画布上绘制顶部文字bitmap
canvas.drawBitmap(markBitmap, 0,0,null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
WaterMarkTestActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//设置bitmap
mImageView.setImageBitmap(resultBitmap);
}
});
}
}).start();
}
/**
* 获得文字水印的图片
* @param width
* @param height
* @return
*/
private Bitmap getMarkTextBitmap(int width, int height){
Util.LOGD(TAG,"width:"+width+" , height:"+height);
Bitmap markBitmap = Bitmap.createBitmap(width*3/2, height*3/2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(markBitmap);
//创建透明画布
canvas.drawColor(Color.TRANSPARENT);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setTextSize(dp2px(WaterMarkTestActivity.this, 18));
Rect bounds = new Rect();
String text = "helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld helloWorld";
paint.getTextBounds(text, 0, text.length(), bounds);
// 获取跟清晰的图像采样
paint.setDither(true);
paint.setFilterBitmap(true);
//为了测试方便,写死了绘制文字的起始位置
canvas.drawText(text, 60,120,paint);
canvas.drawText(text, 120,240,paint);
canvas.drawText(text, 120,360,paint);
canvas.drawText(text, 120,480,paint);
canvas.save(Canvas.ALL_SAVE_FLAG);
//将该文字图片倾斜45度
Matrix matrix = new Matrix();
matrix.postScale(1f,1f);
matrix.postRotate(-45);
Bitmap rotateBitmap = Bitmap.createBitmap(markBitmap, width/4, 0, width,height, matrix, true);
return rotateBitmap;
}
/**
* dip转pix
* @param context
* @param dp
* @return
*/
public static int dp2px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
注意事项:如果直接在UI线程中绘制图片,如果图片较大的话,耗时操作会导致白屏