Question

I want to add watermark to images just like flipboard does.

As you can see text is added at the bottom of the images with black transparent background. I want to do the exact same thing. Till now I've managed to write text on image but I am not able to make it's background black transparent just like the above picture.

Here's my code so far which I found from here.

public Bitmap mark(Bitmap src, String watermark) {
    int w = src.getWidth();
    int h = src.getHeight();

    Shader shader = new LinearGradient(0, 0, 100, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);

    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);
    Paint paint = new Paint();
    paint.setColor(Color.WHITE);
    paint.setTextSize(50);
    paint.setAntiAlias(true);
    paint.setShader(shader);
    paint.setUnderlineText(false);
    canvas.drawText(watermark, 10 , h-15, paint);

    return result;
}
Was it helpful?

Solution

I think it doesn't require gradient, you can draw it using simple color and using drawRect() method.

Sample code is below, i gonna take the black background size as 25% of whole image.

public Bitmap mark(Bitmap src, String watermark) {
    int w = src.getWidth();
    int h = src.getHeight();

    Paint bgPaint=new Paint();
    bgPaint.setColor(Color.parse("AA000000"));  //transparent black,change opacity by changing hex value "AA" between "00" and "FF"

    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);
    Paint paint = new Paint();
    paint.setColor(Color.WHITE);
    paint.setTextSize(50);
    paint.setAntiAlias(true);
    paint.setUnderlineText(false);

    //should draw background first,order is important
    int left=0;
    int right=w;
    int bottom=h;
    int top=bottom-(h*.25);
    canvas.drawRect(left,top,right,bottom,bgPaint);

    canvas.drawText(watermark, 10 , h-15, paint);

return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top