2015年12月27日 星期日

Center text on a bitmap

Reference:

http://www.skoumal.net/en/android-how-draw-text-bitmap/

Code snippet:

Bitmap cloneMarkerBitmap = oriMarkerBitmap.copy(Bitmap.Config.ARGB_8888,true);
Canvas canvas = new Canvas(cloneMarkerBitmap);
Paint textPaint = new Paint();
textPaint.setColor(mResources.getColor(R.color.white));
textPaint.setTextSize(convertDpToPixel(12));
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);

// draw text to the Canvas center
String markerNumber = Integer.toString(number);
Rect bounds = new Rect();
textPaint.getTextBounds(markerNumber, 0, markerNumber.length(), bounds);
int x = (cloneMarkerBitmap.getWidth())/2;
int y = (cloneMarkerBitmap.getHeight() + bounds.height())/2;
canvas.drawText(markerNumber, x, y, textPaint);

...............

    public float convertDpToPixel(float dp) {
        DisplayMetrics metrics = mResources.getDisplayMetrics();
        float px = dp * metrics.density;
        return px;
    }

沒有留言: