7

我想将 UIScrollView 的背景图像设置为可拉伸图像。我试过:

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

但它不是伸展的。

我能做些什么?

4

3 回答 3

3

如果您想利用 的可调整大小的属性UIImage,您需要使用UIImageView. 正如您所注意到的,如果您将其设置为背景颜色,它将不起作用。如果必须修复它,只需创建一个UIImageView并将其放在具有相同框架的后面,或者如果您希望它滚动,则在您的内部具有相同的大小......UIScrollViewUIScrollViewcontentSize

于 2013-03-18T17:41:00.873 回答
1

UIImageView在您的案例集中添加图像

yourImageView.contentMode = UIViewContentModeScaleAspectFill;

您可以将其设置为以下任何一项

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

AnsUIImageView在你里面加这个scrolView

另一种方法是您可以根据需要使用以下方法获取/创建图像大小。

使用以下具有特定高度宽度的方法与图像

+ (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;
}

此方法返回NewImage,具有您指定的特定大小。

于 2013-03-18T14:51:17.693 回答
0

试试这个

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]; 
于 2013-03-18T15:02:29.757 回答