Home > Blockchain >  Why CATextLayer render half width comma "," to full width comma ","
Why CATextLayer render half width comma "," to full width comma ","

Time:07-20

below is the code

import UIKit
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let txtLayer = CATextLayer()
txtLayer.frame = CGRect(x: 10, y: 10, width: 150, height: 50)
txtLayer.foregroundColor = UIColor.red.cgColor
txtLayer.string = ",,"
txtLayer.contentsScale = UIScreen.main.scale

view.layer.addSublayer(txtLayer)
let b = UILabel(frame: CGRect(x: 10, y: 90, width: 40, height: 20))
b.text = ",,"
b.textColor = UIColor.red
view.addSubview(b)

comma render image

I want to CATextLayer render "," like UILabel to display correct symble “,” ,not "," . How can I do?

CodePudding user response:

CATextLayer and UILabel use different fonts by default. You can see this by printing their font properties:

print(txtLayer.font!)
print(b.font!)

This prints these for me:

<UICTFont: 0x7fe3718061d0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 36.00pt
<UICTFont: 0x7fe371909400> font-family: ".SFUI-Regular"; font-weight: normal; font-style: normal; font-size: 17.00pt

If you set them both to the same font, and to the same size so that it's even more obvious, you'll see that the text they display look exactly the same.

let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let txtLayer = CATextLayer()
txtLayer.frame = CGRect(x: 10, y: 10, width: 150, height: 100)
txtLayer.foregroundColor = UIColor.red.cgColor
txtLayer.string = ",,"
txtLayer.contentsScale = UIScreen.main.scale
txtLayer.font = UIFont.systemFont(ofSize: 50) as CTFont
txtLayer.fontSize = 50

view.layer.addSublayer(txtLayer)
let b = UILabel(frame: CGRect(x: 10, y: 140, width: 150, height: 100))
b.text = ",,"
b.textColor = UIColor.red
b.font = .systemFont(ofSize: 50)
view.addSubview(b)

enter image description here

  • Related