在android中以编程方式添加文本到图像

我想创build一个应用程序,就像开放屏幕的android.Idynamic添加图像到tableLayout的行。 我只在xml文件中定义了tableLayout,其余的代码是在java中。 我已经成功添加图像,但我没有得到任何帮助设置该图像的文本(我想显示一个文本下的图像)和图像是一个特定的填充。如何做?提前致谢。

Solutions Collecting From Web of "在android中以编程方式添加文本到图像"

你可以做的是把一个TextView覆盖到一个ImageView使用RelativeLayout 🙂

使用以下function在图像上书写文字:

private BitmapDrawable writeTextOnDrawable(int drawableId, String text) { Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId) .copy(Bitmap.Config.ARGB_8888, true); Typeface tf = Typeface.create("Helvetica", Typeface.BOLD); Paint paint = new Paint(); paint.setStyle(Style.FILL); paint.setColor(Color.WHITE); paint.setTypeface(tf); paint.setTextAlign(Align.CENTER); paint.setTextSize(convertToPixels(mContext, 11)); Rect textRect = new Rect(); paint.getTextBounds(text, 0, text.length(), textRect); Canvas canvas = new Canvas(bm); //If the text is bigger than the canvas , reduce the font size if(textRect.width() >= (canvas.getWidth() - 4)) //the padding on either sides is considered as 4, so as to appropriately fit in the text paint.setTextSize(convertToPixels(mContext, 7)); //Scaling needs to be used for different dpi's //Calculate the positions int xPos = (canvas.getWidth() / 2) - 2; //-2 is for regulating the x position offset //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center. int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ; canvas.drawText(text, xPos, yPos, paint); return new BitmapDrawable(getResources(), bm); } public static int convertToPixels(Context context, int nDP) { final float conversionScale = context.getResources().getDisplayMetrics().density; return (int) ((nDP * conversionScale) + 0.5f) ; } 

我成功实现了在图像上添加文字的这个问题。 只要看看下面的代码。 首先将一个视图作为相对布局,在该布局之后,使用EditText之后的ImageView以及该button之后。 给每一个ID。 在下面写一个loadBitmapFromView函数。

 public Bitmap loadBitmapFromView(View v) { Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_8888); Canvas c = new Canvas(b); v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); v.draw(c); return b; } 

并点击button。

  Bitmap bitmap = loadBitmapFromView(relativeLayout); File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "folderName"); if (!dir.exists()) dir.mkdirs(); File file = new File(dir, "capture.jpg"); try { FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); imageView.setImageBitmap(bitmap); } catch (Exception e) { Log.e("ExpressionEditImageActivity", "Error, " + e); } 

请享用…