Reply to comment

Android - vypisujeme text do bitmapy

Rychlý návod, jak na Androidu vypsat libovolný text do bitmapy načtené z resources.

V prvním kroku načteme bitmapu z resources. Jelikož takto získané bitmapy jsou imutabilní (není možné je měnit) musíme si nejprve vytvořit mutabilní (měnitelnoou) kopii. Další objekt, který budeme potřebovat je Paint, abychom měli text hezky vyhlazený, vytvoříme si antialiazovaný Paint. Pak už jen nastavíme barvu, velikost, stíneček a můžeme kreslit. Pozor, velikost textu se zadává v pixelech, takže je nutné ručně si pixely převést na dip vynásobením dle aktuálního DPI.

Tak, teď už sice můžeme kreslit, ale nevíme kam. Taže si spočítáme x a y souřadnice na které pak text vypíšeme. Nejdřív si text změříme a pak už je to vcelku jednoduchá matematika. Jenom musíme mít na paměti, že počítáme pozici levého spodního rohu textu.

public 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();
  // set default bitmap config if none
  if(bitmapConfig == null) {
    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
  }
  // resource bitmaps are imutable, 
  // so we need to convert it to mutable one
  bitmap = bitmap.copy(bitmapConfig, true);
 
  Canvas canvas = new Canvas(bitmap);
  // new antialised Paint
  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  // text color - #3D3D3D
  paint.setColor(Color.rgb(61, 61, 61));
  // text size in pixels
  paint.setTextSize((int) (14 * scale));
  // text shadow
  paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
 
  // draw text to the Canvas center
  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;
}

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <h4>
  • You can enable syntax highlighting of source code with the following tags: <code>, <c>, <cpp>, <csharp>, <css>, <drupal5>, <drupal6>, <html>, <java>, <javascript>, <latex>, <mysql>, <php>, <postgresql>, <python>, <ruby>, <sql>, <xml>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.

© 2012 Vladislav Skoumal |
Webmail Home Back To Top