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; } }
时间: 2024-10-20 09:59:49