|
| 1 | +// |
| 2 | +// LayerTree.Builder.Text.swift |
| 3 | +// SwiftDraw |
| 4 | +// |
| 5 | +// Created by Simon Whitty on 26/8/22. |
| 6 | +// Copyright 2022 Simon Whitty |
| 7 | +// |
| 8 | +// Distributed under the permissive zlib license |
| 9 | +// Get the latest version from here: |
| 10 | +// |
| 11 | +// https://github.com/swhitty/SwiftDraw |
| 12 | +// |
| 13 | +// This software is provided 'as-is', without any express or implied |
| 14 | +// warranty. In no event will the authors be held liable for any damages |
| 15 | +// arising from the use of this software. |
| 16 | +// |
| 17 | +// Permission is granted to anyone to use this software for any purpose, |
| 18 | +// including commercial applications, and to alter it and redistribute it |
| 19 | +// freely, subject to the following restrictions: |
| 20 | +// |
| 21 | +// 1. The origin of this software must not be misrepresented; you must not |
| 22 | +// claim that you wrote the original software. If you use this software |
| 23 | +// in a product, an acknowledgment in the product documentation would be |
| 24 | +// appreciated but is not required. |
| 25 | +// |
| 26 | +// 2. Altered source versions must be plainly marked as such, and must not be |
| 27 | +// misrepresented as being the original software. |
| 28 | +// |
| 29 | +// 3. This notice may not be removed or altered from any source distribution. |
| 30 | +// |
| 31 | + |
| 32 | +// Convert a DOM.SVG into a layer tree |
| 33 | + |
| 34 | +import Foundation |
| 35 | +#if canImport(CoreText) |
| 36 | +import CoreText |
| 37 | +#endif |
| 38 | + |
| 39 | +extension LayerTree.Builder { |
| 40 | + |
| 41 | +#if canImport(CoreText) |
| 42 | + static func makeXOffset(for text: String, with attributes: LayerTree.TextAttributes) -> LayerTree.Float { |
| 43 | + let font = CTFontCreateWithName(attributes.fontName as CFString, |
| 44 | + CGFloat(attributes.size), |
| 45 | + nil) |
| 46 | + guard let bounds = text.toPath(font: font)?.boundingBoxOfPath else { return 0 } |
| 47 | + switch attributes.anchor { |
| 48 | + case .start: |
| 49 | + return LayerTree.Float(bounds.minX) |
| 50 | + case .middle: |
| 51 | + return LayerTree.Float(-bounds.midX) |
| 52 | + case .end: |
| 53 | + return LayerTree.Float(-bounds.maxX) |
| 54 | + } |
| 55 | + } |
| 56 | +#else |
| 57 | + static func makeXOffset(for text: String, with attributes: LayerTree.TextAttributes) -> LayerTree.Float { |
| 58 | + return 0 |
| 59 | + } |
| 60 | +#endif |
| 61 | + |
| 62 | + |
| 63 | +} |
0 commit comments