Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.content.res.Resources;

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Color;

import android.graphics.Paint;

public class Main {
    public static Bitmap addLabelToBitmap(Bitmap src, String label) {
        float densityFactor = Resources.getSystem().getDisplayMetrics().density;
        final float textPadding = src.getWidth() * 0.05f;

        Bitmap result = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(12 * densityFactor);
        textPaint.setColor(Color.WHITE);
        textPaint.setStrokeWidth(2 * densityFactor);
        textPaint.setShadowLayer(1 * densityFactor, 0, 0, Color.BLACK);

        float textWidth = textPaint.measureText(label);

        float scaleFactor = (src.getWidth() - textPadding * 2) / textWidth;

        canvas.drawBitmap(src, 0, 0, textPaint);

        canvas.save();
        canvas.scale(scaleFactor, scaleFactor);
        float textPosX = (src.getWidth() / scaleFactor - textWidth) / 2;
        float textPosY = (src.getHeight() - textPadding) / scaleFactor;

        canvas.drawText(label, textPosX, textPosY, textPaint);
        canvas.restore();
        return result;
    }
}