I'm trying to draw text in the centre of shapes in iOS, an example would be Microsoft Office's insert shape see: https://www.dropbox.com/s/cgqyyuvy6hcv5g8/Screenshot%202014-01-21%2013.48.17.png
I have an array of coordinates that are used to form the shape, which works fine for creating the actual shape.
My first tactic was following this stackoverflow question: Core Text With Asymmetric Shape on iOS however I can only get it to draw the text at the bottom of the shape. Is there any way to centre the text vertically and horizontally?
I then had a look at the new TextKit but I got stuck with how to subclass NSTextContainer to accept either a CGPath or an array of coordinates to create the text container to draw inside.
My backup solution is to use Core Text to draw the text at the centre coordinate of a shape, however this will cause the text to draw outside of the shape on some shapes such as a right angled triangle.
Alternatively, are there any other methods I could use to get some text somewhat in the centre of a shape?
Thank you,
Danielle.
That's a bit tricky. First you have to create a context. (bounds.size is the size of the image)
Then get the text's bounding box: (font is the font you want to use)
draw your text into the context (x and y marks the center of the image)
Get the image
End image context
I haven't tested it, but it's the way to go.
Swift 3 Version of Luca Davanzo's answer
Swift 2.0 compatible.
My purpose was draw a circle shape with centered text inside.
}
With this utility we can easy create an image in this way:
I cherrypicked from these answers and from related questions - none of them were truly satisfying - and came up with this simple solution:
The result (nevermind the colours):