Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

swift - SwiftUI offset Text() by font size

How can I offset a Text such that exactly splits in the middle of the character. The problem that I face is that the character is not split nicely. What I have so far:

Text("8")
    .font(.system(size: size, design: fontDesign))
    .foregroundColor(fontColor)
    .offset(x: 0, y: size/2)
    .frame(width: size, height: size/2, alignment: .bottom)
    .background(Color.black)
    .clipShape(Rectangle())

Text("8")
    .font(.system(size: size, design: fontDesign))
    .foregroundColor(fontColor)
    .offset(x: 0, y: -size/2)
    .frame(width: size, height: size/2, alignment: .top)
    .background(Color.black)
    .clipShape(Rectangle())

This produces the following output:

enter image description here

I know that I can adjust the offset such that it aligns nicely (with size=50, the y-offset would be 36 resp. -36 to align it). However, the size must be variable. How can this be done?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example that seems to be working. For each Text(), set the frame @ 100% and then add a 2nd frame, cutting the first frame in half and aligning to .top / .bottom.

struct AlignmentTest: View {
    
    let size: CGFloat = 36
    let fontDesign = Font.Design.default
    let fontColor = Color.black
    let lineHeight: CGFloat = 100
    let text: String = "This is a TEST run! 888"
    
    var body: some View {
        VStack(spacing: 0) {
            Text(text)
                .font(.system(size: size, design: fontDesign))
                .foregroundColor(fontColor)
                .frame(height: lineHeight / 2) // frame1: Set height @ 100%
                .background(Color.red)
                .frame(height: lineHeight / 4, alignment: .top) // frame2: Cut frame1 half & align to top
                .clipped() // Clip result to frame2

            Text(text)
                .font(.system(size: size, design: fontDesign))
                .foregroundColor(fontColor)
                .frame(height: lineHeight / 2)
                .background(Color.blue)
                .frame(height: lineHeight / 4, alignment: .bottom)
                .clipped()
        }
    }
}

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...