I'm trying to use RectangleCountour library to make a rounded rectangles with rounded corners between lines behind all the text strings separately in UILabel. The parameters (x, y, width and height) are dynamic and i have to count it for every string. When I try to count it for every line and don't match with the text inside the label or set the rectangle for all the label based on the biggest width. Here is an example of the code where I just set the random parameters:
override func draw(_ rect: CGRect) {
if let customFont = customFont {
font = customFont
}
let rects: [CGRect] = [
CGRect(x: 10, y: 20, width: 30, height: 40),
CGRect(x: 20, y: 30, width: 50, height: 60),
]
let contour: IsoOrientedContour = rects.contour()
let roundedPath: CGPath = contour.cgPath(cornerRadius: customCornerRadius ?? 6)
let uiPath = UIBezierPath(cgPath: roundedPath)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setFillColor(customBackgroundColor?.cgColor ?? UIColor(red: 94/255, green: 17/255, blue: 82/255, alpha: 0.58).cgColor)
context.addPath(roundedPath)
context.closePath()
context.fillPath()
super.draw(rect)
}
}
And this is what I want Expectation Seems like I have to draw the rect for every string based on its parameters, but I don't know how to count them. Or maybe you know the other libraries to implement this?
The demo code in RectangleContour shows how to do this with a
UITextView.The idea is to use
NSLayoutManager.enumerateLineFragmentsto get all the rects used by each line.To do the same with a
UILabel, you just need to create anNSTextStoragethat contains the label's text, aNSTextContainerthe same size as the label, and aNSLayoutManagerthat lays out the text. Then you can also useNSLayoutManager.enumerateLineFragments.Example code:
Note that
sizeToFitis important here becauseUILabels centre their text vertically, butNSTextContainers don't do that.NSLayoutManagerwould produce rects that are aligned to the top of the label.