
This video is only available to subscribers. Start a subscription today to get access to this and 419 other videos.
Text
Episode
#288
|
9 minutes
| published on
July 21, 2017
| Uses swift-3.0, Xcode-8.3
Subscribers Only
In this episode, Sam shows how to draw text using Core Graphics. With this technique you can easily add text to images for pre-rendering, a technique we will see in another episode in this series.
This episode is part of a series: Dive Into Core Graphics.
1. Intro 2 min |
2. Basic Shapes 7 min |
3. Paths 17 min |
4. Colors 9 min |
5. Gradients 11 min |
6. Clipping Paths 6 min |
7. Context Transforms 10 min |
8. Images 7 min |
9. Text 9 min |
10. Offscreen Rendering 12 min |
11. Custom CALayer 13 min |
12. Pie Progress View 7 min |
13. Watermarking Photos 6 min |
14. Working in AppKit 8 min |
Links
Setting up
We will just fill our view with white, then define a string we can draw.
guard let context = UIGraphicsGetCurrentContext() else { return }
let colorSpace = CGColorSpaceCreateDeviceRGB()
let color = CGColor(colorSpace: colorSpace, components: [1, 1, 1, 1])!
context.setFillColor(color)
context.fill(bounds)
let string = "Hello World"
Defining Text Attributes
To configure text color, font, alignment, and other text attributes, we will use NSAttributedString
. This takes a dictionary of attributes to apply to the string.
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes: [String: Any] = [
NSFontAttributeName: UIFont.systemFont(ofSize: 40),
NSForegroundColorAttributeName: UIColor.blue,
NSParagraphStyleAttributeName: paragraph
]
Using NSString’s Drawing Method
NSString
can draw itself, which is the simplest approach.
(string as NSString).draw(at: CGPoint(x: 20, y: 20), withAttributes: attributes)
Drawing with NSAttributedString
We can also draw an attributed string similarly:
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
attributedString.addAttribute(NSFontAttributeName,
value: UIFont.systemFont(ofSize: 40, weight: UIFontWeightBold),
range: NSRange(location: 6, length: 5))
let size = attributedString.size()
attributedString.draw(in: AVMakeRect(aspectRatio: size, insideRect: bounds))
Drawing with UILabel
Another quick way to do this (on iOS) is top leverage UILabel
’s drawing.
let label = UILabel()
label.attributedText = attributedString
label.drawText(in: bounds)