Reputation: 1
I'm trying to center text in a CGrect inside a PDF. I can generate the PDF and draw rects, but ive been looking for a method to draw certain text into certain rects, as the text is filled in by the user, i cant get it to dynamically stay centered. I feel ive run myself down a path and cant find a way back out. Can anyone shed any light or even suggest a fix?
This method produces an error for me
Cannot convert value of type 'CGRect' to expected argument type 'CGFloat'
Heres an example:
func addActNumber(pageRect: CGRect) -> CGFloat {
let titleFont = UIFont.systemFont(ofSize: 18.0, weight: .bold)
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: titleFont]
let attributedTitle = NSAttributedString(string:"Act \(actNumber)", attributes: titleAttributes)
let ActNumberStringSize = attributedTitle.size()
let ActNumberRect = CGRect (x: 10 , y: 35, width: 191.6, height: 25 )
let titleStringRect = CGRect(x: (ActNumberRect - ActNumberStringSize.width) / 2.0 , y: 35, width: 191.6 ,
height: 25)
attributedTitle.draw(in: titleStringRect)
return titleStringRect.origin.y + titleStringRect.size.height
}
Upvotes: 0
Views: 602
Reputation: 329
Use the NSMutableParagraphStyle() for your text alignment in a rectangle. For example:
func alignText(value:String, x: Int, y: Int, width:Int, height: Int, alignment: NSTextAlignment, textFont: UIFont){
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
let attributes = [ NSAttributedString.Key.font: textFont,
NSAttributedString.Key.paragraphStyle: paragraphStyle ]
let textRect = CGRect(x: x,
y: y,
width: width,
height: height)
value.draw(in: textRect, withAttributes: attributes)
}
and run the function with:
alignText(value: "Your Text", x: 0, y: 0, width: 300, height: 20, alignment: .right, textFont: UIFont.systemFont(ofSize: 10, weight: .bold))
Upvotes: 2