UIScrollView with pattern image as background

2019-04-11 08:15发布

问题:

here is the problem I'm facing: I am making a UIScrollView which will have a pattern image to fill the background. That is to say, I need a background to scroll with the UIScrollView. A good example for this is the Game Center app, on the iPad. The background will scroll smoothly with scrollview.

Currently I have two ways to realize this effect, but neither of them offered good performance. First I tried this

self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:kRLCastViewBGUnit]];

but unfortunately, the scrolling performance was very bad and occupied too much memory.

Then I tried to use CGContextDrawTiledImage in the drawRect like this:

- (void)drawRect:(CGRect)rect
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(currentContext, 0, rect.size.height);
    CGContextScaleCTM(currentContext, 1.0, -1.0);

    CGContextClipToRect(currentContext, rect);
    CGRect centerTileRect = CenterTileRect;
    CGContextDrawTiledImage(currentContext, centerTileRect, [ResourceProvider backgroundTileImageRef]);

}

It's still not satisfactory on the new iPad. I must have done something wrong or misused some methods, because the Game Center performs just great when it scrolls. Anyone can offer me a solution to solve the performance issue for the UIScrollView background? Thanks a lot!!

回答1:

You should use an UITableView instead. In this you can set cell.backgroundView easily.

UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake:(0.0,0.0,320.0, height)];
backgroundView.image = [UIImage imageNamed:@"Shelf.jpeg"];
cell.backgroundView = backgroundView;

And If you really want to use only UIScrollView then take only one cell background image and image width should be same of scrollView's width because colorWithPatternImage: method work like tiled property.

Take Only this image into your project and use it as backgroundColor of UIScrollView.

[scrollView setContentSize:CGSizeMake(320.0, 1000.0)];
[scrollView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"cellImage.png"]]];