2012-05-17 22 views
37

Tengo una vista, y quiero establecer BackrougColor para esta vista por UIImage. El código como:ios: colorWithPatternImage, expandir la imagen de pantalla completa

self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backImage.png"]]; 

el problema es: la backImage'frame es pequeña que la vista. cómo estirar UIImage a mi punto de vista completo. Uso razonable de UIImageView puede alcanzar.

alguien tiene una buena idea?

actualización:

No puedo subir una imagen.

De esta manera: el tamaño de backImge es 30 * 30, y el tamaño de mi punto de vista es 1024 * 700, cuando uso myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backImage.png"]];

El resultado es backgroup de myview tiene muchas 'backImage.png'. mi objetivo es tener una 'backImage.png' streth full myview.

+0

puede mostrar alguna imagen, para llevarnos un poco más de idea sobre el tema? – rishi

+0

Podría ser este su problema - http://stackoverflow.com/questions/8651276/background-color-colorwithpatternimage-not-filling-entire-view-for-ipad – rishi

Respuesta

23

Hasta donde yo sé, no puede cambiar el tamaño de la imagen de patrón del fondo directamente. La manera más fácil es simplemente cambiar su imagen para que se ajuste al tamaño de fotograma de su vista principal. O puede volver a dibujar su imagen para que se ajuste al tamaño de su vista principal.

UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake(10.f, 100.f, 300.f, 100.f)]; 
UIImage * targetImage = [UIImage imageNamed:@"backImage.png"]; 

// redraw the image to fit |yourView|'s size 
UIGraphicsBeginImageContextWithOptions(yourView.frame.size, NO, 0.f); 
[targetImage drawInRect:CGRectMake(0.f, 0.f, yourView.frame.size.width, yourView.frame.size.height)]; 
UIImage * resultImage = UIGraphicsGetImageFromCurrentImageContext();  
UIGraphicsEndImageContext(); 

[yourView setBackgroundColor:[UIColor colorWithPatternImage:resultImage]]; 
112

Tienen un intento.

self.layer.contents = (id)[UIImage imageNamed:@"freshBackground.png"].CGImage;

+2

Funciona perfectamente :) – delannoyk

+1

Sí funciona bien, pero cualquier idea como? –

+0

Aquí hay un tutorial que lo explica: http: //www.raywenderlich.com/2502/calayers-tutorial-para-ios-introducción-a-calayers-tutorial – SirNod

2

Y en base a la respuesta de Kjuly, si desea que la imagen que se va insertada correctamente en el centro en lugar de ser estirado, utilice este método para obtener la nueva imagen:

#pragma mark - Image 
+(UIImage*)imageFitInCenterForSize:(CGSize)inSize forSourceImage:(UIImage*)inImage 
{ 
    // redraw the image to fit |yourView|'s size 
    CGSize imageOriginalSize = inImage.size; 
    UIImage *resultImage = nil; 
    if (imageOriginalSize.width<=inSize.width && imageOriginalSize.height<=inSize.height) 
    { 
     UIGraphicsBeginImageContextWithOptions(inSize, NO, 0.f); 
     [inImage drawInRect:CGRectMake((inSize.width-imageOriginalSize.width)/2.0, (inSize.height-imageOriginalSize.height)/2.0, imageOriginalSize.width, imageOriginalSize.height)]; 
     resultImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } 
    return resultImage; 
} 

El mismo con la variante sobrecargado:

+(UIImage*)imageFitInCenterForSize:(CGSize)inSize forSourceImage:(UIImage*)inImage xOffset:(CGFloat)inXOffset yOffset:(CGFloat)inYOffset 
{ 
    // http://stackoverflow.com/questions/10629403/ios-colorwithpatternimage-stretch-image-full-screen 
    // redraw the image to fit |yourView|'s size 
    CGSize imageOriginalSize = inImage.size; 
    UIImage *resultImage = nil; 
    if (imageOriginalSize.width<=inSize.width && imageOriginalSize.height<=inSize.height) 
    { 
     UIGraphicsBeginImageContextWithOptions(inSize, NO, 0.f); 
     [inImage drawInRect:CGRectMake((inSize.width-imageOriginalSize.width)/2.0+inXOffset, (inSize.height-imageOriginalSize.height)/2.0+inYOffset, imageOriginalSize.width, imageOriginalSize.height)]; 
     resultImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } 
    return resultImage; 
} 
+0

Esta ayuda mw muy bien – CRDave

3

respuesta de world000 traducida a Swift:

self.layer.contents = UIImage(named: "freshBackground.png")?.CGImage 
0

Aquí se basa en comentarios anteriores, una versión que escala la imagen primero, luego cosechas para llenar el aspecto proporcionalmente.

func imageScaledToFillSize(size: CGSize, image: UIImage) -> UIImage 
{ 
    let aspect = image.size.width/image.size.height; 
    UIGraphicsBeginImageContextWithOptions(size, false, 0) 
    if (size.width/aspect <= size.height) { 
     let resizedImg = self.imageScaledToSize(CGSize(width: size.height * aspect, height: size.height), image: image) 
     resizedImg.drawInRect(CGRectMake((size.width - resizedImg.size.width)/2, 0, resizedImg.size.width, resizedImg.size.height)) 
    } else { 
     let resizedImg = self.imageScaledToSize(CGSize(width: size.width, height: size.width/aspect), image: image) 
     resizedImg.drawInRect(CGRectMake(0, (size.height-resizedImg.size.height)/2, resizedImg.size.width, resizedImg.size.height)) 
    } 
    let imageR = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return imageR; 
} 

func imageScaledToSize(size: CGSize, image: UIImage) -> UIImage { 
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0); 
    image.drawInRect(CGRectMake(0.0, 0.0, size.width, size.height)) 
    let imageR = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext(); 
    return imageR; 
} 
0

I utilizar el siguiente método a:

  1. dibujar la imagen dentro de los límites específicos (que lo hace escala)
  2. utilizar la imagen resultante como un patrón.

Código:

UIGraphicsBeginImageContext(self.window.frame.size); 
[[UIImage imageNamed:@"background"] drawInRect:self.window.bounds]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
self.window.backgroundColor = [UIColor colorWithPatternImage:image]; 
Cuestiones relacionadas