天天看點

Android為圖檔添加水印文字

import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageView iv = (ImageView) findViewById(R.id.imageView);

		//為簡單期間,就使用Android原生的小機器人為目标圖檔
		Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);

		// Drawable -> Bitmap:Drawable 轉換成 Bitmap。
		BitmapDrawable bd = (BitmapDrawable) drawable;
		Bitmap bmp = bd.getBitmap();

		// 為Bitmap添加水印
		Bitmap bitmap = createWatermark(bmp, "@ Zhang Phil");

		iv.setImageBitmap(bitmap);
	}

	// 為圖檔target添加水印文字
	// Bitmap target:被添加水印的圖檔
	// String mark:水印文章
	private Bitmap createWatermark(Bitmap target, String mark) {
		int w = target.getWidth();
		int h = target.getHeight();

		Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);

		Paint p = new Paint();

		// 水印的顔色
		p.setColor(Color.RED);

		// 水印的字型大小
		p.setTextSize(10);

		p.setAntiAlias(true);// 去鋸齒

		canvas.drawBitmap(target, 0, 0, p);

		// 在左邊的中間位置開始添加水印
		canvas.drawText(mark, 0, h / 2, p);

		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();

		return bmp;
	}
}
           

繼續閱讀