How do you draw text with a border on a MapView in Android?

五迷三道 提交于 2019-11-26 23:56:41

The easiest way to do this is with a Stroke... something like this:

@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
    Paint strokePaint = new Paint();
    strokePaint.setARGB(255, 0, 0, 0);
    strokePaint.setTextAlign(Paint.Align.CENTER);
    strokePaint.setTextSize(16);
    strokePaint.setTypeface(Typeface.DEFAULT_BOLD);
    strokePaint.setStyle(Paint.Style.STROKE);
    strokePaint.setStrokeWidth(2);

    Paint textPaint = new Paint();
    textPaint.setARGB(255, 255, 255, 255);
    textPaint.setTextAlign(Paint.Align.CENTER);
    textPaint.setTextSize(16);
    textPaint.setTypeface(Typeface.DEFAULT_BOLD);

    canvas.drawText("Some Text", 100, 100, strokePaint);
    canvas.drawText("Some Text", 100, 100, textPaint);

    super.draw(canvas, mapView, shadow);
}

This will draw a border of 2 pixels around the outside of the text then draw the text over the top of it, giving you the illusion of an outline.

Also, it may be worth setting the Paints up in the constructor then just reusing them.

Instead of this code (from the first answer)

canvas.drawText("Some Text", 100, 100, strokePaint);
canvas.drawText("Some Text", 100, 100, textPaint);

try to use the same with Path:

Path path = new Path();
String text = "Some Text";
tp.getTextPath(text, 0, text.length(), 0, 100, path);
canvas.drawPath(path, strokePaint);
canvas.drawPath(path, textPaint);

looks better?

The half-answer, which may or may not be good enough (it was in my case), is to set a shadow:

textPaint.setShadowLayer(3, 0, 0, Color.BLACK);

The shadow helps the text stand out a lot, but isn't quite as good as a black border would be. I'm still curious how to solve the original question.

This is a complete shot in the dark and there might be a better way, but if you create 4 copies of the text, set their color to black, then shift each layer by 1 pixel diagonally, it would create an illusion of a border. So if your text is positioned at [100,100], the 4 shadows would need to be positioned at [99,99], [99,101], [101,99] and [101,101], like this:

canvas.drawText("Some Text", 99, 99, borderPaint);
canvas.drawText("Some Text", 99, 101, borderPaint);
canvas.drawText("Some Text", 101, 99, borderPaint);
canvas.drawText("Some Text", 101, 101, borderPaint);

canvas.drawText("Some Text", 100, 100, textPaint);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!