简体   繁体   English

向像Snapchat这样的图片中添加带有灰色背景的文本? Android / Java

[英]Add text with grey background to pictures like Snapchat does? Android/Java

          Bitmap newBm = ...
          Canvas canvas = new Canvas(newBm);
          Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
          paint.setColor(Color.WHITE);
          paint.setTextSize((int) (44 * scale));
          Rect bounds = new Rect();
          paint.getTextBounds(gText, 0, gText.length(), bounds);
          canvas.drawText(gText, x, y, paint);

I drew text on the Bitmap like so. 我像这样在位图上绘制文本。 How could I get a grey background that is the same height as the text but covers the whole screen?? 如何获得与文本相同高度但覆盖整个屏幕的灰色背景?

The best way to see and learn how these sort of things are done with well written code is to look at the android source code itself. 查看和学习如何通过编写良好的代码完成这些事情的最佳方法是查看android源代码本身。 For example here is the onDraw method for a TextView it includes additional stuff you won't probably need like compoundPadding, but you can follow it through and get the basic concept of how it's done. 例如,这里是TextViewonDraw方法,它包含您可能不需要的其他内容(例如compoundPadding),但是您可以按照它进行操作并获得完成操作的基本概念。

You could use a Rect . 您可以使用Rect Before drawing the text draw the Rect to the screen: 在绘制文本之前,将Rect绘制到屏幕上:

int screenWidth = getApplicationContext().getResources().getDisplayMetrics().widthPixels; Rect greyBack = new Rect(0,top,screenWidth,bottom); Paint paint = new Paint(); paint.setARGB(128, 100, 100, 100); //added alpha because Snapchat has translucent //grey background canvas.drawRect(greyBack, paint);

top and bottom need to be coordinates above and below the text. topbottom必须是文本上方和下方的坐标。 You could use y 's value and take away a bit for top and add a bit for bottom . 您可以使用y的值,在top取一点,在bottom取一点。 How much you add/subtract is up to you and changes the height of the greyBack background. 加/减多少取决于您,并更改greyBack背景的高度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM