0

I have a hexagon jpg file that looks like this:

enter image description here

I would like to put a number of my choice inside the center of it. so the final output would look something like this:

enter image description here

I want the number to be directly centered always. Is there a way to do this with the shape tag in android xml ? I also need to specify a width and height of the hexagon. I dont think the shape tag will help here as i already have the shape defined. do you think my best bet is to use a button and write the number on it while keeping the hexagon as a background ?

Community
  • 1
  • 1
j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • A Button or a TextView with custom background would do the trick for you, I guess. – Juan Martinez Mar 30 '17 at 18:32
  • ok. i wasn't sure if there was a less expensive way to do this. because i'll have to inflate this view whenever i need it. but thanks – j2emanue Mar 30 '17 at 18:34
  • Or any viewgroup, such as linearlayout or relativelayout, with the image as background and a separate textview centered in it. – JHH Mar 30 '17 at 18:38

1 Answers1

2

There are two main ways that I can think of you could use. Like you said, you could use a Button/TextView and set the background as the hexagon resource. As you said though, that requires inflating that view every time. The other way would be to use a Canvas and draw the number directly on the image, then put the image into an ImageView or other similar view. To draw on the image:

int fontSize = 200; //set your font size
Bitmap baseImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.hexagon); //load the hexagon image
Bitmap image = baseImage.copy(Bitmap.Config.ARGB_8888, true); //create mutable bitmap for canvas. see: http://stackoverflow.com/a/13119762/1896516

//the "paint" to use when drawing the text
Paint paint = new Paint(); //see here for all paint options: https://developer.android.com/reference/android/graphics/Paint.html
paint.setTextSize(fontSize); //sets your desired font size
paint.setColor(Color.BLACK); //set the desired color of the text
paint.setTextAlign(Paint.Align.CENTER); //set the alignment of the text

Canvas canvas = new Canvas(image); //create a canvas from the bitmap
canvas.drawText("#", image.getWidth()/2, image.getHeight()/2 + fontSize/4, paint); //draw the number onto the hexagon

ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(image);

You may need to play with the text positioning depending on if your image has borders, etc. In addition, note that I haven't really tested these two against eachother for performance, so I'm not sure which one will be the most effecient way in the end. That said, the first way is likely easier to do as it will take care of positioning by itself. Hope this helps!

T3KBAU5
  • 1,861
  • 20
  • 26