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?


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


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.


试试这个

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]; 
链接地址: http://www.djcxy.com/p/70080.html

上一篇: 提供og:图像不够大

下一篇: 如何将UIScrollView的背景图像设置为可伸缩图像?