7

I want to set UIScrollView's background image as a stretchable image. I tried:

UIImage* backgroundImage =[[UIImage imageNamed:@"background"]
                               resizableImageWithCapInsets:UIEdgeInsetsMake(100, 0, 0, 0) ];
self.scrollView.backgroundColor = [UIColor colorWithPatternImage:backgroundImage];

But it is not stretching.

What can I do?

iPatel
  • 46,010
  • 16
  • 115
  • 137
Burak
  • 5,706
  • 20
  • 70
  • 110

3 Answers3

3

If you want to take advantage of the resizable properties of the UIImage, you need to use an UIImageView. As you've noticed, it doesn't work if you set it as a background color. Just create an UIImageView and put it behind your UIScrollView with the same frame if it has to be fixed, or inside your UIScrollView with the same size as the contentSize if you want it to scroll...

Guillaume
  • 4,331
  • 2
  • 28
  • 31
1

Add image in UIImageView and in your case set

yourImageView.contentMode = UIViewContentModeScaleAspectFill;

you can set it to any of the following

UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight

Ans add This UIImageView in you scrolView.

Another way is you can use following method for get/create image size as you want.

Use following method with specific hight and width with image

+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
    CGSize newSize = CGSizeMake(width, height);
    float widthRatio = newSize.width/image.size.width;
    float heightRatio = newSize.height/image.size.height;

    if(widthRatio > heightRatio)
    {
        newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
    }
    else
    {
        newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
    }


    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

This method return NewImage, with specific size that you specify.

iPatel
  • 46,010
  • 16
  • 115
  • 137
0

Try this one

UIImage* backgroundImage =[[UIImage imageNamed:@"back.jpg"]
                           resizableImageWithCapInsets:UIEdgeInsetsMake(100, 0, 0, 0) ];
UIGraphicsBeginImageContextWithOptions(self.scrollView.bounds.size, NO, 0.0);
[backgroundImage drawInRect:self.scrollView.bounds];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.scrollView.backgroundColor = [UIColor colorWithPatternImage:newImage]; 
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110