如何在SwiftUI中笔画文字? [英] How to make text stroke in SwiftUI?

查看:176
本文介绍了如何在SwiftUI中笔画文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在SwiftUI中进行笔画操作或在文本上添加边框,而不是Text()项.

I'm trying to make text-stroke in SwiftUI or add a border on my text, in the letters not the Text() item.

有可能吗?

我想用边框来产生这种效果:

I want to make this effect with the border:

推荐答案

我认为没有开箱即用"的方法.
到目前为止(测试版5),我们只能将笔画应用于Shapes.

I don't think there's a way for doing that "out of the box".
So far (beta 5) we can apply strokes to Shapes only.

例如:

struct SomeView: View {
    var body: some View {
        Circle().stroke(Color.red)
    }
}

但同样,该功能不适用于Text.

But again that isn’t available for Text.

UIViewRepresentable

UIViewRepresentable

另一种方法是通过UIViewRepresentable将良好的UIKit \ NSAttributedString与SwiftUI一起使用.

Another approach would be to use the good ol' UIKit \ NSAttributedString with SwiftUI via UIViewRepresentable.

像这样:

import SwiftUI
import UIKit

struct SomeView: View {
    var body: some View {
        StrokeTextLabel()
    }
}

struct StrokeTextLabel: UIViewRepresentable {
    func makeUIView(context: Context) -> UILabel {
        let attributedStringParagraphStyle = NSMutableParagraphStyle()
        attributedStringParagraphStyle.alignment = NSTextAlignment.center
        let attributedString = NSAttributedString(
            string: "Classic",
            attributes:[
                NSAttributedString.Key.paragraphStyle: attributedStringParagraphStyle,
                NSAttributedString.Key.strokeWidth: 3.0,
                NSAttributedString.Key.foregroundColor: UIColor.black,
                NSAttributedString.Key.strokeColor: UIColor.black,
                NSAttributedString.Key.font: UIFont(name:"Helvetica", size:30.0)!
            ]
        )

        let strokeLabel = UILabel(frame: CGRect.zero)
        strokeLabel.attributedText = attributedString
        strokeLabel.backgroundColor = UIColor.clear
        strokeLabel.sizeToFit()
        strokeLabel.center = CGPoint.init(x: 0.0, y: 0.0)
        return strokeLabel
    }

    func updateUIView(_ uiView: UILabel, context: Context) {}
}

#if DEBUG
struct SomeView_Previews: PreviewProvider {
    static var previews: some View {
        SomeView()
    }
}
#endif

结果

当然,您必须调整NSAttributedString的属性(大小,字体,颜色等)以生成所需的输出.为此,我建议使用视觉属性字符串 macOS应用.

Of course you have to tweak the attributes (size, font, color, etc) of the NSAttributedString to generate the desired output. For that I would recommend the Visual Attributed String macOS app.

这篇关于如何在SwiftUI中笔画文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆