2009-11-09 15 views
5

Quiero dibujar texto en una vista, rotar 90 °. Soy bastante nuevo en el desarrollo de iPhone, y hurgando en la web revela una serie de soluciones diferentes. Intenté algunas y generalmente termino recortando el texto.iPhone: ¿Dibujar texto girado?

¿Qué está pasando aquí? I am dibujo en un espacio bastante pequeño (una celda de vista de tabla), pero tiene que haber una forma "correcta" de hacer esto ... ¿verdad?


Editar: Aquí hay un par de ejemplos. Estoy tratando de mostrar el texto "" a lo largo de la barra negra a la izquierda.

  1. primer intento, desde RJShearman on the Apple Discussions

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSelectFont (context, "Helvetica-Bold", 16.0, kCGEncodingMacRoman); 
    CGContextSetTextDrawingMode (context, kCGTextFill); 
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); 
    CGContextSetTextMatrix (context, CGAffineTransformRotate(CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f), M_PI/2)); 
    CGContextShowTextAtPoint (context, 21.0, 55.0, [_cell.number cStringUsingEncoding:NSUTF8StringEncoding], [_cell.number length]); 
    CGContextRestoreGState(context); 
    

    Attempt one. The one and part of the two are clipped out. http://dev.deeptechinc.com/sidney/share/iphonerotation/attempt1.png

  2. Segundo intento, desde zgombosi on iPhone Dev SDK. Resultados idénticos (la fuente era un poco más pequeña aquí, por lo que hay menos recorte).

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGPoint point = CGPointMake(6.0, 50.0); 
    CGContextSaveGState(context); 
    CGContextTranslateCTM(context, point.x, point.y); 
    CGAffineTransform textTransform = CGAffineTransformMakeRotation(-1.57); 
    CGContextConcatCTM(context, textTransform); 
    CGContextTranslateCTM(context, -point.x, -point.y); 
    [[UIColor redColor] set]; 
    [_cell.number drawAtPoint:point withFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]]; 
    CGContextRestoreGState(context); 
    

    Attempt two. There is almost identical clipping http://dev.deeptechinc.com/sidney/share/iphonerotation/attempt2.png

+0

De hecho, hay algunas maneras de hacerlo. Proporcionar algunos detalles sobre qué exactamente ha intentado y cómo exactamente no funcionó (¿cómo/dónde se recortó?) Haría que sea más fácil responder de manera útil. –

+0

Detalle proporcionado. – s4y

Respuesta

7

Resulta que la celda de mi tabla era siempre inicializada 44px de alto independientemente de la altura de la fila, por lo que todo mi dibujo fue recortado 44px desde la parte superior de la celda.

Para dibujar celdas más grandes que era necesario establecer de autoresizingMask la vista de contenido con

cellContentView.autoresizingMask = UIViewAutoresizingFlexibleHeight; 

o

cellContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 

... y drawRect se llama con el tamaño correcto. En cierto modo, esto tiene sentido, porque UITableViewCell 's initWithStyle:reuseIdentifier: no hace mención del tamaño de la celda, y solo la vista de tabla realmente sabe cuán grande va a ser cada fila, según su propio tamaño y la respuesta de su delegado a tableView:heightForRowAtIndexPath: .

leí el Quartz 2D Programming Guide hasta que el modelo y las funciones de dibujo comenzaron a tener sentido, y el código para llamar a mi texto girado se convirtió en simple y obvia:

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSaveGState(context); 
CGContextRotateCTM(context, -(M_PI/2)); 
[_cell.number drawAtPoint:CGPointMake(-57.0, 5.5) withFont:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]]; 
CGContextRestoreGState(context); 

Gracias por los consejos, parece que estoy todo listo.

1

Usted sabe sobre el método UITableViewDelegate heightForRowAtIndexPath ¿verdad?

Aquí está un simple tutorial on various graphics level methods. Suponiendo que sepa cuán grande es el texto, debería poder dimensionar adecuadamente el tamaño de fila de la vista de tabla.

Además, yo verificaría para asegurarse de que los límites después de cualquier transformación realmente cumplan con sus expectativas. (Utilice un depurador o una declaración de registro para verificar esto).

+0

Sé sobre 'tableView: heightForRowAtIndexPath:', la fila está bien. El texto se recorta durante la transformación y termina cortado en el medio de la celda. – s4y

+0

¿Podría mostrarnos el código específico que utiliza para hacer la transformación? –

2

Aquí hay un consejo. Supongo que estás haciendo este dibujo en drawRect. ¿Por qué no dibujas un marco alrededor de drawRect para ver qué tan grande es el rect y si es por eso que tienes clipping?

Una alternativa es poner su texto en un UILabel, y luego girarlo 90 grados cuando haga sus celdas en cellForRowAtIndexPath.

+2

La sugerencia de mahboudz probablemente sea su camino de menor resistencia. Puede rotar el UILabel 90deg con esto: [label setTransform: CGAffineTransformMakeRotation (DegreesToRadians (-90.0f))]; Tendrás que calcular la altura de tu celda según el ancho de la etiqueta. -Matt –

0

Después de descubrir que necesitaba agregar lo siguiente a la parte superior de mi archivo, me gustó el enfoque de Matt. Muy simple.

#define degreesToRadian(x) (M_PI * (x)/180.0) 

La sugerencia de mahboudz probablemente sea su camino de menor resistencia. Puede rotar el UILabel 90deg con esto: [label setTransform: CGAffineTransformMakeRotation (DegreesToRadians (-90.0f))]; Tendrás que calcular la altura de tu celda según el ancho de la etiqueta. -Matt - Matt Largo 10 de noviembre a las 0:09

3

Uso: -

label.transform = CGAffineTransformMakeRotation(- 90.0f * M_PI/180.0f); 

donde la etiqueta es el objeto de UILabel.

+0

Gracias, @Sorted! En realidad, no estaba usando un 'UILabel' - estaba dibujando en una celda de vista de tabla personalizada. – s4y

1

a lo que dijo @Sidnicious, y lo que me recolectados a lo largo de desbordamiento de pila, quiero dar un ejemplo de uso - adjunta mi código para dibujar una regla completamente hacia el lado izquierdo de la pantalla, con los números de girar:

ruler screenshot

RulerView : UIView 


    // simple testing for iPhones (check for device descriptions to get all iPhones + iPads) 
    - (float)getPPI 
    { 
     switch ((int)[UIScreen mainScreen].bounds.size.height) { 
      case 568: // iPhone 5* 
      case 667: // iPhone 6 
       return 163.0; 
       break; 

      case 736: // iPhone 6+ 
       return 154.0; 
       break; 

      default: 
       return -1.0; 
       break; 
     } 
    } 

    - (void)drawRect:(CGRect)rect 
    { 
     [[UIColor blackColor] setFill]; 


     float ppi = [self getPPI]; 

     if (ppi == -1.0) // unable to draw, maybe an ipad. 
      return; 

     float linesDist = ppi/25.4; // ppi/mm per inch (regular size iPad would be 132.0, iPhone6+ 154.0) 

     float linesWidthShort = 15.0; 
     float linesWidthMid = 20.0; 
     float linesWidthLong = 25.0; 

     for (float i = 0, c = 0; i <= self.bounds.size.height; i = i + linesDist, c = c +1.0) 
     { 
      bool isMid = (int)c % 5 == 0; 
      bool isLong = (int)c % 10 == 0; 

      float linesWidth = isLong ? linesWidthLong : isMid ? linesWidthMid : linesWidthShort; 
      UIRectFillUsingBlendMode((CGRect){0, i, linesWidth, .5} , kCGBlendModeNormal); 



      /* FONT: Numbers without rotation (yes, is short) 
      if (isLong && i > 0 && (int)c % 10 == 0) 
       [[NSString stringWithFormat:@"%d", (int)(c/10)] drawAtPoint:(CGPoint){linesWidthLong +2, i -5} withAttributes:@{ 
                                   NSFontAttributeName: [UIFont systemFontOfSize:9], 
                                   NSBaselineOffsetAttributeName: [NSNumber numberWithFloat:1.0] 
                                   }]; 
      */ 


      // FONT: Numbers with rotation (yes, requires more effort) 
      if (isLong && i > 0 && (int)c % 10 == 0) 
      { 
       NSString *str = [NSString stringWithFormat:@"%d", (int)(c/10)]; 
       NSDictionary *attrs = @{ 
             NSFontAttributeName: [UIFont systemFontOfSize:9], 
             NSBaselineOffsetAttributeName: [NSNumber numberWithFloat:0.0] 
             }; 
       CGSize textSize = [str sizeWithAttributes:attrs]; 


       CGContextRef context = UIGraphicsGetCurrentContext(); 
       CGContextSaveGState(context); 

       CGContextRotateCTM(context, +(M_PI/2)); 
       [str drawAtPoint:(CGPoint){i - (textSize.width/2), -(linesWidthLong + textSize.height +2)} withAttributes:attrs]; 

       CGContextRestoreGState(context); 
      } 

     } 
    }