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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With