Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set UIScrollView's background image as a stretchable image?

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?

like image 768
Burak Avatar asked Mar 18 '13 14:03

Burak


2 Answers

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...

like image 60
Guillaume Avatar answered Nov 16 '22 01:11

Guillaume


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.

like image 29
iPatel Avatar answered Nov 15 '22 23:11

iPatel