2011-11-15 17 views
6

Quiero hacer una aplicación para el iPhone similar a algunas aplicaciones de tarjetas de felicitación, donde podría escribir texto sobre algunas imágenes de fondo preparadas previamente (tarjetas).Agregar texto sobre una imagen en Xcode

  • ¿Cómo puedo escribir este texto?
  • Cómo guardar la imagen de fondo + el texto en un archivo de imagen?

Gracias.

+1

núcleo gráfico podría ser la dirección correcta. – dasdom

+1

puede hacer un controlador en blanco con la barra de estado oculta y hacer una captura de pantalla después de terminar la edición. Creo que UIImagePNGRepresentation es lo que necesitas para eso. –

+0

Gracias por sus respuestas. Sí, creo que tu solución es mucho más fácil que utilizar Tha Core Graphics, me centraré en eso. Si lo entiendo, quiere decir que preparo la imagen de fondo en una vista y agrego un uiTextfield con bachground transparente sobre ella, dejo que el usuario ingrese el texto y luego realice una scereenshot. Es eso puede ser? – hafedh

Respuesta

10

Aquí hay un método que graba una cadena en una imagen. Puede ajustar el tamaño de fuente y otros parámetros para configurarlo a su gusto.

/* Creates an image with a home-grown graphics context, burns the supplied string into it. */ 
- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img { 

UIGraphicsBeginImageContext(img.size); 

CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height); 
[img drawInRect:aRectangle]; 

[[UIColor redColor] set];   // set text color 
NSInteger fontSize = 14; 
if ([text length] > 200) { 
    fontSize = 10; 
} 
UIFont *font = [UIFont boldSystemFontOfSize: fontSize];  // set text font 

[ text drawInRect : aRectangle      // render the text 
     withFont : font 
    lineBreakMode : UILineBreakModeTailTruncation // clip overflow from end of last line 
     alignment : UITextAlignmentCenter ]; 

UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); // extract the image 
UIGraphicsEndImageContext();  // clean up the context. 
return theImage; 
} 
+0

Gracias Rayfleck, se ve genial! – hafedh

+0

@Rayfleck Sé que esta es una respuesta antigua, pero la encontré hoy y funciona muy bien, ¡así que gracias! Solo tengo una pregunta. ¿Hay alguna manera de modificar este código para dibujar la cadena verticalmente (texto girado 90 grados en sentido contrario a las agujas del reloj) – Ryan

+0

@Ryan - primero gire la imagen en sentido HORARIO, luego grábela en el texto, luego gírela hacia atrás. Mira aquí http://www.catamount.com/forums/viewtopic.php?f=21&t=967 para ver algunas útiles extensiones de UIImage para hacer las rotaciones. – Rayfleck

5

Gracias Rayfleck! Funcionó.

Para añadir compatibilidad opcional con pantallas de retina (reparaciones de cartas agitadas durante la versión de imagen '@ 2x' scale up):

reemplazar:

UIGraphicsBeginImageContext(img.size); 

con condicional:

if (UIGraphicsBeginImageContextWithOptions != NULL) 
    UIGraphicsBeginImageContextWithOptions(img.size,NO,0.0); 
else 
    UIGraphicsBeginImageContext(img.size); 
+0

Gracias Rob, esto funciona muy bien. ¿Qué está haciendo exactamente? – Ryan

+0

¡Me alegra ayudar! La instrucción IF es una comprobación rápida para ver si UIGraphicsBeginImageContextWithOptions está disponible (ios4 o posterior). Si no, entonces puedes asumir que no es retina. Si es así, estás pasando las opciones: 1 - tamaño de la imagen (área de texto); 2 - fondo transparente (opaco = NO); y 3 - '0.0', que le dice al dispositivo que use su propia escala (las pantallas de la retina serán predeterminadas a 2.0 (?)) – Rob

0

Actualización para ios7 ...

/* Creates an image with a home-grown graphics context, burns the supplied string into it. */ 
    - (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img { 

     UIGraphicsBeginImageContext(img.size); 

     CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height); 
     [img drawInRect:aRectangle]; 

     [[UIColor redColor] set];   // set text color 
     NSInteger fontSize = 14; 
     if ([text length] > 200) { 
      fontSize = 10; 
     } 

     UIFont *font = [UIFont fontWithName:@"Courier" size:fontSize]; 
     NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
     paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; 


     paragraphStyle.alignment = NSTextAlignmentRight; 
     NSDictionary *attributes = @{ NSFontAttributeName: font, 
             NSParagraphStyleAttributeName: paragraphStyle, 
             NSForegroundColorAttributeName: [UIColor whiteColor]}; 
     [text drawInRect:aRectangle withAttributes:attributes]; 

     UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); // extract the image 
     UIGraphicsEndImageContext();  // clean up the context. 
     return theImage; 
    } 
0

Este enfoque tiene en cuenta la escala de la pantalla y es muy intuitiva

UIImage * img = ... 
    UIImageView * iV = [[UIImageView alloc] initWithImage:img]; 
    UILabel * l = [[UILabel alloc] initWithFrame:iV.bounds]; 
    l.textAlignment = ...; 
    l.adjustsFontSizeToFitWidth = YES; 
    l.textColor = ...; 
    l.font = ...; 
    l.text = ...; 

    [iV addSubview:l]; 

    UIGraphicsBeginImageContextWithOptions(iV.bounds.size, NO, 0); 
    [iV.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage * finalImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return finalImage