In my app, I have a bunch of UIBezierPath
s that I import from SVG files using this thing, which all represent irregular shapes. I want to draw texts inside the shapes so as to "label" those shapes. Here's an example:
I want to draw the text "A" inside the shape. Basically, this'd be done in the draw(_:)
method of a custom UIView
, and I expect to call a method with a signature such as:
func drawText(_ text: String, in path: UIBezierPath, fontSize: CGFloat) {
// draws text, or do nothing if there is not enough space
}
After some looking online, I found this post, which seems to always draw the string in the centre of the image. This is not what I want. If I put the A
in the centre of the bounding box of the UIBezierPath
(which I know I can get with UIBezierPath.bounds
), it would be outside of the shape. This is probably because the shape is concave.
Note that the texts are quite short so I don't need to worry about line wrapping and stuff.
Of course, there are lots of places inside the shape I could put the "A" in, I just want a solution that chooses any one place that can show the text in a reasonable size. One way I have thought of is to find the largest rectangle that can be inscribed in the shape, and then draw the text in the centre of that rectangle. I've found this post that does this in Matlab, and it seems like a really computation-intensive to do... I'm not sure this is a good solution.
How should I implement drawText(_:in:fontSize:)
?
To avoid being an XY question, here's some background:
The shapes I'm handling are actually borders of administrative regions. In other words, I'm drawing a map. I don't want to use existing map APIs because I want my map to look very crude. It's only going to show the borders of administrative regions, and labels on them. So surely I could just use whatever algorithm the map APIs are using to draw the labels on their maps, right?
This question is not a duplicate of this, as I know I can do that with UIBezierPath.contains
. I'm trying to find a point. It's not a duplicate of this either, as my question is about drawing text inside a path, not on.