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

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.

/**
* Adds a watermark on the given image.
*/
public static Bitmap addWatermark(Resources res, Bitmap source) {
int w, h;
Canvas c;
Paint paint;
Bitmap bmp, watermark;

Matrix matrix;
float scale;
RectF r;

w = source.getWidth();
h = source.getHeight();

// Create the new bitmap
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);

// Copy the original bitmap into the new one
c = new Canvas(bmp);
c.drawBitmap(source, 0, 0, paint);

// Load the watermark
watermark = BitmapFactory.decodeResource(res, R.drawable.android_mo);
// Scale the watermark to be approximately 10% of the source image height
scale = (float) (((float) h * 0.10) / (float) watermark.getHeight());

// Create the matrix
matrix = new Matrix();
matrix.postScale(scale, scale);
// Determine the post-scaled size of the watermark
r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
matrix.mapRect(r);
// Move the watermark to the bottom right corner
matrix.postTranslate(w - r.width(), h - r.height());

// Draw the watermark
c.drawBitmap(watermark, matrix, paint);
// Free up the bitmap memory
watermark.recycle();

return bmp;
}

Sources

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