Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Comportamiento inconsistente del interletraje en NSAttributedString

Necesito usar el atributo Kern de NSAttributedString . Como puedo ver en la documentación, el valor predeterminado de ese atributo es 0.0. Pero me enfrenté a un comportamiento extraño para la frase Hello, world (para la frase "Hola" todo bien):

 NSDictionary<NSString*, id>* attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:12]}; NSString* text = @"Hello, World"; NSAttributedString* string = [[NSAttributedString alloc] initWithString:text attributes:attributes]; CGSize size1 = [string size]; NSMutableDictionary<NSString*, id>* attributesWithKernel = [attributes mutableCopy]; attributesWithKernel[NSKernAttributeName] = @(0.0); NSAttributedString* stringWithKern = [[NSAttributedString alloc] initWithString:text attributes:attributesWithKernel]; CGSize size2 = [stringWithKern size]; XCTAssertTrue(CGSizeEqualToSize(size1, size2)); //here test falls //size1 = size1 = (width = 68.8125, height = 14.3203125) //size2 = (width = 69.515625, height = 14.3203125)

Para que size1 y size2 sean iguales, el interletraje debe ser igual -7.105427357601002e-15 , sé que esto está muy cerca de 0.0, pero es extraño, porque esto cambia el ancho casi un píxel.
NSAttributedString tiene el mismo comportamiento en Objective-C y en Swift , ejemplo para swift:

 let text = "Hello, World" let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)] let str = NSAttributedString(string: text, attributes: attributes) let size = str.size() var attributesWithKern = attributes attributesWithKern[NSAttributedString.Key.kern] = NSNumber(value: 0.0) let strWithKern = NSAttributedString(string: text, attributes: attributesWithKern) let sizeWithKern = strWithKern.size() XCTAssertTrue(size == sizeWithKern)

¿Cómo puedo solucionar este comportamiento?

PD Ahora simplemente NSKernAttributeKey de una cadena de atributos si la clave es igual a 0.0, pero no creo que sea una buena solución.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Creo que los documentos aquí están equivocados, y vale la pena abrir un radar al respecto. Cuando no se establece ningún valor, se interpreta como "interletraje normal". Cuando se establece 0, se interpreta como "deshabilitar interletraje", por lo que el ancho es un poco más amplio (el interletraje suele ser ligeramente negativo, lo que hace que los caracteres de par de interletraje, como "W" y "o" en esta fuente, sean un poco más cerca). No creo que haya ninguna forma de solicitar explícitamente "kerning predeterminado" sin eliminar el atributo.

Para sus propósitos, creo que está haciendo lo correcto al eliminar el valor cuando es cero, porque desea un interletraje predeterminado, no deshabilitar el interletraje.

La razón por la que su pequeño valor negativo está funcionando es porque no es cero, por lo que no está deshabilitando el kerning, pero es tan pequeño que el comportamiento es muy, muy cercano al valor predeterminado, y se encuentra con la precisión de Doble en los cálculos intermedios. (o posiblemente la precisión de Float, dependiendo de cómo se implemente internamente). Debería encontrar que su prueba pasa para cualquier valor más pequeño (más cercano a cero) que este, no solo ese valor. En mis pruebas también funciona el 7e-15 positivo, por ejemplo.

over 4 years ago · Santiago Trujillo Report

0

Hice algunas pruebas basadas en su código y confirmo este comportamiento que parece un error. El punto es que algunas cadenas de letras son iguales, para otras no. Por ejemplo, las cadenas con "Hello Mo" o "Hello Oo" son iguales, pero, por ejemplo, "Hello WoWoWo" difieren mucho. Entonces vemos aquí que se agrega algo de kerning para "W" sin ninguna razón. También puede depender de la fuente elegida, aunque no la probé. Veo aquí la única solución que ha usado: eliminar NSKernAttributeKey si es igual a 0.

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!