SwiftUI How can I get the correct font size for CATextLayer

42 views Asked by At

I am using SWiftUI and have a video editing application . A person selects a video and we display it along with the date the video was taken . The initial overlay is size 14 and if the person saves that video along with the date we are noticing that the date in the saved video is smaller than the overlay sized 14 . Can someone give suggestions on how to correct this issue ?

This is the Overlay

struct DateOverlay: View {
    @Binding var DateColor: Color
    @State var DateOfVideo: String = ""
    var body: some View {
        Text(DateOfVideo)
            .foregroundColor(DateColor)
            .font(.custom("Helvetica", size: 14))
    }
}

Then when the video gets saved this is the function responsible for the position of the overlay and the size of the overlay text on the saved video .

func DateTextLayer(Composition: AVMutableVideoComposition, videoModel: VideoModel,NaturalSize: CGSize) -> CATextLayer {
    
    let textLayer = CATextLayer()
    textLayer.string = videoModel.VideoDate
    textLayer.foregroundColor = videoModel.DateColor?.cgColor
    textLayer.alignmentMode = .center
    textLayer.contentsScale = UIScreen.main.scale

    let scaleFactor = UIScreen.main.scale
    print("Scale Factor is \(scaleFactor)") // 3
    let adjustedFontSize = 14.0 * scaleFactor // Adjusted for screen scale this still makes it too small
    textLayer.fontSize = adjustedFontSize
    textLayer.font = UIFont(name: "Helvetica", size: adjustedFontSize)
    textLayer.bounds = CGRect(x: 0, y: 0, width: NaturalSize.width, height: 100)
    textLayer.position = CGPoint(x: Composition.renderSize.width / 2, y: Composition.renderSize.height / 2)

    return textLayer
}

I am not sure how the conversion should go, I know that I can manually increase the scaleFactor but then that would defeat the purpose since we will have different videos saved . Any suggestion would be great

This is the Overlay OverLay

This is the font size when saved

Saved

This is the difference side by side

Difference

0

There are 0 answers