Advertisement
warodri

Android: Overlap images and text

Mar 2nd, 2012
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. /* this is a simple overlay: one bitmap over another */
  2. public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
  3. {
  4. Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(),
  5. bmp1.getHeight(), bmp1.getConfig());
  6. Canvas canvas = new Canvas(bmOverlay);
  7. canvas.drawBitmap(bmp1, new Matrix(), null);
  8. canvas.drawBitmap(bmp2, new Matrix(), null);
  9. return bmOverlay;
  10. }
  11.  
  12. /* this is a bit more complex overlay - includes 2 lines of text and a transparent PNG on the background */
  13. public static Bitmap overlaybottom( Context context, Bitmap bmp1,
  14. String textLine1, String textLine2 )
  15. {
  16. // final bitmap
  17. Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(),
  18. bmp1.getHeight(), bmp1.getConfig());
  19. Canvas canvas = new Canvas(bmOverlay);
  20. canvas.drawBitmap(bmp1, new Matrix(), null);
  21.  
  22. // the second bitmap is a transparent PNG (make it the height you need for 2 lines
  23. Bitmap bmp2 = BitmapFactory.decodeResource( context.getResources(),
  24. R.drawable.transparent_png );
  25.  
  26. // this is a bit hard-coded but it's just to give an idea...
  27. boolean singleLine = false;
  28. boolean doubleLine = false;
  29.  
  30. if ( textLine1 != null && textLine1.trim().length() > 0 )
  31. singleLine = true;
  32.  
  33. if ( textLine2 != null && textLine2.trim().length() > 0 )
  34. doubleLine = true;
  35.  
  36. // ** pinto bitmap al pie
  37. int top = bmp1.getHeight() - bmp2.getHeight();
  38. int left = 0;
  39.  
  40. if ( doubleLine == false )
  41. top += ( bmp2.getHeight() / 2 );
  42.  
  43. canvas.drawBitmap(bmp2, left, top, null);
  44.  
  45. if ( singleLine )
  46. {
  47. // we have one line of text - set font sizes and paddings
  48. final int FONT_SIZE = 35;
  49. final int FONT_SIZE_SMALL = 25;
  50. final int PADDING = 30;
  51.  
  52. Paint paint = new Paint();
  53. paint.setTextSize( FONT_SIZE );
  54. paint.setShadowLayer(5, 5, 5, Color.parseColor("#ffffff"));
  55. paint.setTypeface(Typeface.DEFAULT_BOLD );
  56.  
  57. top = top + PADDING;
  58. left = PADDING / 2;
  59.  
  60. // draw the text for the first line
  61. canvas.drawText( textLine1, left, top, paint );
  62.  
  63. if ( doubleLine )
  64. {
  65. // we have a second line of text - reset font size
  66. paint.setTextSize( FONT_SIZE_SMALL );
  67. paint.setTypeface(Typeface.DEFAULT );
  68.  
  69. // with 2 lines of text, our transparent PNG should be higer
  70. top += paint.getTextSize() + ( PADDING / 2 );
  71.  
  72. // finally, draw the text over the transparent PNG
  73. canvas.drawText( textLine2, left, top, paint );
  74. }
  75. }
  76.  
  77. return bmOverlay;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement