Search code examples
androidandroid-maps-v2

I can't draw text in front of bitmap for market in Google map API V2?


Hi, genious!
What's the problem?
I tried to draw text in front of marker. I'm going to get clear bitmap and draw text but bitmap is still clear - where is the text?
I tried to convert View to bitmap but it's also wasn't good idea.
PS: scale >= 1

mMap.addMarker(new MarkerOptions()
.position(new LatLng(56.83789, 60.5986))                              .icon(BitmapDescriptorFactory.fromBitmap(drawTextToBitmap(getApplicationContext(), R.drawable.ic_maps_marker,"19"))));

    //here I'm trying to draw text bitmap
             public static Bitmap drawTextToBitmap(Context gContext,int gResId,String gText) {
                    Resources resources = gContext.getResources();
                    float scale = resources.getDisplayMetrics().density;
                    Bitmap bitmap =
                            BitmapFactory.decodeResource(resources, gResId);

                    android.graphics.Bitmap.Config bitmapConfig =
                            bitmap.getConfig();
                    if(bitmapConfig == null) {
                        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
                    }
                    bitmap = bitmap.copy(bitmapConfig, true);

                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                    paint.setColor(Color.BLACK);
                    paint.setTextSize((int) (14 * scale));
                    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

                    Rect bounds = new Rect();
                    paint.getTextBounds(gText, 0, gText.length(), bounds);
                    int x = (bitmap.getWidth() - bounds.width())/2;
                    int y = (bitmap.getHeight() + bounds.height())/2;

                    canvas.drawText(gText, x * scale, y * scale, paint);

                    return bitmap;
                }

Solution

  • Density was only necessary to determinate the size of the text. To draw text on canvas should not use scale, because of displacements x and y calculated for particular bitmap.
    Try this:

    canvas.drawText(gText, x, y, paint);
    

    This work on 4 devices: