Search code examples
androidandroid-canvasdraw

Draw a text middle of an image android


I have to place marker on map view and write a number on marker. I have done that, but text alignment varies in different resolution. bellow is the reference code

        float xVal = (float) curScreenCoords.x;  // Point curScreenCoords
        float yVal = (float) curScreenCoords.y-20; // Point curScreenCoords
        Bitmap bitmap = BitmapFactory.decodeResource ( context.getResources() , ( R.drawable.pin_number ) ) ;
        canvas.drawBitmap(bitmap, xVal, yVal, getInnerPaint()); 

        public Paint getInnerPaint() {
         if (innerPaint == null) {
             innerPaint = new Paint();
         }
        innerPaint.setARGB(255, 117, 161, 220); // blue
        innerPaint.setAntiAlias(true);  
        innerPaint.setStyle(Style.FILL);
        return innerPaint;
        }
        canvas.drawText(String.valueOf(10), xVal+20, yVal+22, getCountPaint()); // 10 is just for example, it can vary to one digit to two to three 
        public Paint getCountPaint() {
        if (innerPaint == null) {
        innerPaint = new Paint();
        }
        innerPaint.setARGB(255, 255, 255, 255); 
        innerPaint.setAntiAlias(true);  
        innerPaint.setStyle(Style.FILL);
        innerPaint.setTextSize(12f);
        innerPaint.setTextAlign(Align.CENTER);
        return innerPaint;
       }

everything works fine, excepting text alignment, this code works fine for 480*800 resolution. Text is perfectly center aligned in canvas. x, y position is perfect on image, but this does not look perfect on 320*480. x and y position of text looks different on this resolution. Can anyone please suggest me what exactly happens wrong? is there any fundamentals for doing the same on different sized devices? Thanks in advance.


Solution

  • Your values curScreenCoords.y-20 and xVal+20, yVal+22 have constant pixel offset for all resolutions, but they should depend on device's pixel density like this:

    xOffset = (int) (13.33f * context.getResources().getDisplayMetrics().density + 0.5f);
    yOffset = (int) (14.67f * context.getResources().getDisplayMetrics().density + 0.5f);
    canvas.drawText(String.valueOf(10), xVal + xOffset, yVal + yOffset, getCountPaint());