Android: Scale a watermark Bitmap over another Bitmap using the Matrix

0 Comments

What I set out to do was to overlay a logo over a photo and it was surprisingly easy with the use of the Matrix class.

image 
No no, not him!

I've littered the code with comments, but if you need any more information leave a comment.

01./**
02. * Adds a watermark on the given image.
03. */
04.public static Bitmap addWatermark(Resources res, Bitmap source) {
05.  int w, h;
06.  Canvas c;
07.  Paint paint;
08.  Bitmap bmp, watermark;
09. 
10.  Matrix matrix;
11.  float scale;
12.  RectF r;
13. 
14.  w = source.getWidth();
15.  h = source.getHeight();
16. 
17.  // Create the new bitmap
18.  bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
19. 
20.  paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
21. 
22.  // Copy the original bitmap into the new one
23.  c = new Canvas(bmp);
24.  c.drawBitmap(source, 0, 0, paint);
25. 
26.  // Load the watermark
27.  watermark = BitmapFactory.decodeResource(res, R.drawable.android_mo);
28.  // Scale the watermark to be approximately 10% of the source image height
29.  scale = (float) (((float) h * 0.10) / (float) watermark.getHeight());
30. 
31.  // Create the matrix
32.  matrix = new Matrix();
33.  matrix.postScale(scale, scale);
34.  // Determine the post-scaled size of the watermark
35.  r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
36.  matrix.mapRect(r);
37.  // Move the watermark to the bottom right corner
38.  matrix.postTranslate(w - r.width(), h - r.height());
39. 
40.  // Draw the watermark
41.  c.drawBitmap(watermark, matrix, paint);
42.  // Free up the bitmap memory
43.  watermark.recycle();
44. 
45.  return bmp;
46.}

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog