Как преобразовать текст swiftui на путь и применить преобразования? Мне удалось извлечь глифы, используя text.topath (), но я сталкиваюсь с проблемами с применением преобразований и должным образом предоставляю результат.
Вот мой текущий подход:
//
// TextToPathView.swift
import SwiftUI
import CoreText
struct TextToPathView: View {
@State private var fontSize: CGFloat = 40
@State private var strokeWidth: CGFloat = 2
@State private var letterSpacing: CGFloat = 2
@State private var curveRadius: CGFloat = 0
@State private var isBold = false
@State private var isItalic = false
@State private var isUnderlined = false
@State private var isCurved = false
@State private var fontColor = Color.black
@State private var strokeColor = Color.red
@State private var alignment: NSTextAlignment = .center
var body: some View {
VStack {
Text("Text to Path Editor")
.font(.title)
.fontWeight(.bold)
.padding(.bottom, 10)
// Use the unified PathView that creates one CGPath for all effects.
PathView(
text: "Hello, SwiftUI!",
fontSize: fontSize,
strokeWidth: strokeWidth,
letterSpacing: letterSpacing,
curveRadius: curveRadius,
isBold: isBold,
isItalic: isItalic,
isUnderlined: isUnderlined,
isCurved: isCurved,
fontColor: UIColor(fontColor),
strokeColor: UIColor(strokeColor),
alignment: alignment
)
.frame(height: 200)
.padding()
Divider().padding()
// Sliders
VStack {
SliderView(value: $fontSize, label: "Font Size", range: 20...100)
SliderView(value: $strokeWidth, label: "Stroke Width", range: 0...5)
SliderView(value: $letterSpacing, label: "Letter Spacing", range: 0...10)
if isCurved {
SliderView(value: $curveRadius, label: "Curve Radius", range: 50...200)
}
}
// Toggles
HStack {
Toggle("Bold", isOn: $isBold)
Toggle("Italic", isOn: $isItalic)
Toggle("Underline", isOn: $isUnderlined)
}
.padding(.top, 10)
Toggle("Curved Text", isOn: $isCurved)
.padding(.top, 5)
// Alignment Picker
Picker("Alignment", selection: $alignment) {
Text("Left").tag(NSTextAlignment.left)
Text("Center").tag(NSTextAlignment.center)
Text("Right").tag(NSTextAlignment.right)
}
.pickerStyle(SegmentedPickerStyle())
.padding(.top, 5)
// Color Pickers
HStack {
VStack {
Text("Font Color")
ColorPicker("", selection: $fontColor)
.frame(width: 50)
}
VStack {
Text("Stroke Color")
ColorPicker("", selection: $strokeColor)
.frame(width: 50)
}
}
.padding(.top, 10)
}
.padding()
}
}
// MARK: - PathView (Creates one CGPath reflecting all effects)
struct PathView: View {
var text: String
var fontSize: CGFloat
var strokeWidth: CGFloat
var letterSpacing: CGFloat
var curveRadius: CGFloat
var isBold: Bool
var isItalic: Bool
var isUnderlined: Bool
var isCurved: Bool
var fontColor: UIColor
var strokeColor: UIColor
var alignment: NSTextAlignment
var body: some View {
GeometryReader { geometry in
if let path = styledTextToPath(
text: text,
font: UIFont.systemFont(ofSize: fontSize),
fontSize: fontSize,
color: fontColor,
strokeColor: strokeColor,
strokeWidth: strokeWidth,
alignment: alignment,
letterSpacing: letterSpacing,
isBold: isBold,
isItalic: isItalic,
isUnderlined: isUnderlined,
isCurved: isCurved,
curveRadius: curveRadius
) {
ZStack {
// Fill the complete text path with the chosen font color.
Path(path)
.fill(Color(fontColor))
// Then stroke the path with the chosen stroke color.
Path(path)
.stroke(Color(strokeColor), lineWidth: strokeWidth)
}
.frame(width: geometry.size.width, height: geometry.size.height)
// Adjust vertical offset as needed.
.offset(y: 50)
}
}
}
}
// MARK: - Create a CGPath that reflects all styling effects.
func styledTextToPath(
text: String,
font: UIFont,
fontSize: CGFloat,
color: UIColor,
strokeColor: UIColor,
strokeWidth: CGFloat,
alignment: NSTextAlignment,
letterSpacing: CGFloat,
isBold: Bool,
isItalic: Bool,
isUnderlined: Bool,
isCurved: Bool,
curveRadius: CGFloat
) -> CGPath? {
// Determine the font traits.
var traits: UIFontDescriptor.SymbolicTraits = []
if isBold { traits.insert(.traitBold) }
if isItalic { traits.insert(.traitItalic) }
var styledFont = font
if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
styledFont = UIFont(descriptor: descriptor, size: fontSize)
}
// Build common attributes.
let attributes: [NSAttributedString.Key: Any] = [
.font: styledFont,
.foregroundColor: color,
.kern: letterSpacing,
.strokeColor: strokeColor,
.strokeWidth: strokeWidth
]
// If not curved, use a simple approach.
if !isCurved {
let attributedString = NSAttributedString(string: text, attributes: attributes)
let line = CTLineCreateWithAttributedString(attributedString)
let totalWidth = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))
let runArray = CTLineGetGlyphRuns(line) as NSArray
let path = CGMutablePath()
for run in runArray {
let run = run as! CTRun
let count = CTRunGetGlyphCount(run)
for index in 0.. < /p>
Текстовый путь не совпадает в кадре. Глифы появляются сдвинуты при использовании cgaffineTransform. src = "https://i.sstatic.net/wjeijry8.png"/>
Подробнее здесь: https://stackoverflow.com/questions/795 ... formations
Как преобразовать текст на путь и применить преобразования? ⇐ IOS
Программируем под IOS
-
Anonymous
1741713393
Anonymous
Как преобразовать текст swiftui на путь и применить преобразования? Мне удалось извлечь глифы, используя text.topath (), но я сталкиваюсь с проблемами с применением преобразований и должным образом предоставляю результат.
[b] Вот мой текущий подход: [/b]
//
// TextToPathView.swift
import SwiftUI
import CoreText
struct TextToPathView: View {
@State private var fontSize: CGFloat = 40
@State private var strokeWidth: CGFloat = 2
@State private var letterSpacing: CGFloat = 2
@State private var curveRadius: CGFloat = 0
@State private var isBold = false
@State private var isItalic = false
@State private var isUnderlined = false
@State private var isCurved = false
@State private var fontColor = Color.black
@State private var strokeColor = Color.red
@State private var alignment: NSTextAlignment = .center
var body: some View {
VStack {
Text("Text to Path Editor")
.font(.title)
.fontWeight(.bold)
.padding(.bottom, 10)
// Use the unified PathView that creates one CGPath for all effects.
PathView(
text: "Hello, SwiftUI!",
fontSize: fontSize,
strokeWidth: strokeWidth,
letterSpacing: letterSpacing,
curveRadius: curveRadius,
isBold: isBold,
isItalic: isItalic,
isUnderlined: isUnderlined,
isCurved: isCurved,
fontColor: UIColor(fontColor),
strokeColor: UIColor(strokeColor),
alignment: alignment
)
.frame(height: 200)
.padding()
Divider().padding()
// Sliders
VStack {
SliderView(value: $fontSize, label: "Font Size", range: 20...100)
SliderView(value: $strokeWidth, label: "Stroke Width", range: 0...5)
SliderView(value: $letterSpacing, label: "Letter Spacing", range: 0...10)
if isCurved {
SliderView(value: $curveRadius, label: "Curve Radius", range: 50...200)
}
}
// Toggles
HStack {
Toggle("Bold", isOn: $isBold)
Toggle("Italic", isOn: $isItalic)
Toggle("Underline", isOn: $isUnderlined)
}
.padding(.top, 10)
Toggle("Curved Text", isOn: $isCurved)
.padding(.top, 5)
// Alignment Picker
Picker("Alignment", selection: $alignment) {
Text("Left").tag(NSTextAlignment.left)
Text("Center").tag(NSTextAlignment.center)
Text("Right").tag(NSTextAlignment.right)
}
.pickerStyle(SegmentedPickerStyle())
.padding(.top, 5)
// Color Pickers
HStack {
VStack {
Text("Font Color")
ColorPicker("", selection: $fontColor)
.frame(width: 50)
}
VStack {
Text("Stroke Color")
ColorPicker("", selection: $strokeColor)
.frame(width: 50)
}
}
.padding(.top, 10)
}
.padding()
}
}
// MARK: - PathView (Creates one CGPath reflecting all effects)
struct PathView: View {
var text: String
var fontSize: CGFloat
var strokeWidth: CGFloat
var letterSpacing: CGFloat
var curveRadius: CGFloat
var isBold: Bool
var isItalic: Bool
var isUnderlined: Bool
var isCurved: Bool
var fontColor: UIColor
var strokeColor: UIColor
var alignment: NSTextAlignment
var body: some View {
GeometryReader { geometry in
if let path = styledTextToPath(
text: text,
font: UIFont.systemFont(ofSize: fontSize),
fontSize: fontSize,
color: fontColor,
strokeColor: strokeColor,
strokeWidth: strokeWidth,
alignment: alignment,
letterSpacing: letterSpacing,
isBold: isBold,
isItalic: isItalic,
isUnderlined: isUnderlined,
isCurved: isCurved,
curveRadius: curveRadius
) {
ZStack {
// Fill the complete text path with the chosen font color.
Path(path)
.fill(Color(fontColor))
// Then stroke the path with the chosen stroke color.
Path(path)
.stroke(Color(strokeColor), lineWidth: strokeWidth)
}
.frame(width: geometry.size.width, height: geometry.size.height)
// Adjust vertical offset as needed.
.offset(y: 50)
}
}
}
}
// MARK: - Create a CGPath that reflects all styling effects.
func styledTextToPath(
text: String,
font: UIFont,
fontSize: CGFloat,
color: UIColor,
strokeColor: UIColor,
strokeWidth: CGFloat,
alignment: NSTextAlignment,
letterSpacing: CGFloat,
isBold: Bool,
isItalic: Bool,
isUnderlined: Bool,
isCurved: Bool,
curveRadius: CGFloat
) -> CGPath? {
// Determine the font traits.
var traits: UIFontDescriptor.SymbolicTraits = []
if isBold { traits.insert(.traitBold) }
if isItalic { traits.insert(.traitItalic) }
var styledFont = font
if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
styledFont = UIFont(descriptor: descriptor, size: fontSize)
}
// Build common attributes.
let attributes: [NSAttributedString.Key: Any] = [
.font: styledFont,
.foregroundColor: color,
.kern: letterSpacing,
.strokeColor: strokeColor,
.strokeWidth: strokeWidth
]
// If not curved, use a simple approach.
if !isCurved {
let attributedString = NSAttributedString(string: text, attributes: attributes)
let line = CTLineCreateWithAttributedString(attributedString)
let totalWidth = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))
let runArray = CTLineGetGlyphRuns(line) as NSArray
let path = CGMutablePath()
for run in runArray {
let run = run as! CTRun
let count = CTRunGetGlyphCount(run)
for index in 0.. < /p>
Текстовый путь не совпадает в кадре. Глифы появляются сдвинуты при использовании cgaffineTransform. src = "https://i.sstatic.net/wjeijry8.png"/>
Подробнее здесь: [url]https://stackoverflow.com/questions/79500624/how-to-convert-text-to-a-path-and-apply-transformations[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия