Reputation: 6500
I have the following code to draw text on an image.How can i draw the text inclined at 90 degree
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: textcolor,
NSAttributedStringKey.paragraphStyle: textStyle
]
text.draw(in: textRect, withAttributes: textFontAttributes)
Upvotes: 1
Views: 315
Reputation: 257789
Here is demo of approach with calculable location
class DemoView: NSView {
override func draw(_ rect: NSRect) {
// .. your drawing code here
NSColor.red.set() // just for demo
rect.fill() // just for demo
if let context = NSGraphicsContext.current?.cgContext {
context.saveGState()
let text: NSString = "Hello World"
let attributes = [
NSAttributedString.Key.foregroundColor: NSColor.white,
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 24)
]
let size = text.size(withAttributes: attributes)
context.translateBy(x: size.height, y: (rect.height - size.width) / 2)
context.rotate(by: CGFloat.pi / 2)
text.draw(at: .zero, withAttributes: attributes)
context.restoreGState()
}
}
}
Upvotes: 3
Reputation: 5554
I have found a nice simple approach - but you will have to play with the co-ordinates a bit. The transformation moves the origin to the bottom-left corner
Most of the answer came from an earlier answer - How to rotate text in NSView? (Mac OS, Cocoa, Swift), but it needed a bit of updating.
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let font = NSFont.boldSystemFont(ofSize: 18)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: NSColor.red,
NSAttributedString.Key.paragraphStyle: textStyle
]
let textRect = CGRect(x: 200, y: 200 , width: 200, height: 100)
"normal".draw(in: textRect, withAttributes: textFontAttributes)
let transf : NSAffineTransform = NSAffineTransform()
transf.rotate(byDegrees: 90)
transf.concat()
"200, -100".draw(at: NSMakePoint(200, -100), withAttributes:textFontAttributes)
"300, -50".draw(at: NSMakePoint(300, -50), withAttributes:textFontAttributes)
}
Upvotes: 2