colorWithPatternImage creates black grids in iphon

2020-03-30 15:53发布

问题:

I have

UIView *topPart = [[UIView alloc] initWithFrame:CGRectMake(9, 0, 302, 318)];
topPart.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern.png"]];
[someScroller addSubview:topPart];
[topPart release];

and I can see the pattern fine when I use a 3gs or the iphone simulator, but when I tested on an actual iPhone 4, I see the pattern images but there are black lines separating each pattern so it looks like a grid. I checked the pattern image and there is no black border or anything .

There was someone with a different problem but it may be the same solution colorWithPatternImage with iPhone 4 Retina Display (image@2x.png)

but they suggested using the -(void)drawRect: method, only problem is i have no idea how to do that.

Thanks

回答1:

I was experiencing the same issue and found it was due to my png being greyscale (not RGB)

To check if this is the case, just select the image in Xcode, show the Utilities sidebar (the one that appears from the right) and look at the Color Space.

To fix this you can use your favourite image editor, but for photoshop do this: Open the greyscale image Select all and copy Create a new document (but this time make sure the colour space is RGB) Paste

Hope it helps :)



回答2:

I figured it out by combining the answers from these 2 posts https://devforums.apple.com/message/259150#259150

How can I use CGContextDrawTiledImage to tile an image?

UIImage *thePattern= [self GetFineTiles:[UIImage imageNamed:@"Feedbackpattern.png"]];
theView.backgroundColor = [UIColor colorWithPatternImage:thePattern];

-(UIImage*)GetFineTiles:(UIImage*)badImage{
    UIGraphicsBeginImageContext(badImage.size);
    CGContextRef imageContext = UIGraphicsGetCurrentContext();
    CGContextDrawTiledImage(imageContext, (CGRect){CGPointZero,badImage.size}, badImage.CGImage);
    UIImage *goodPattern = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return goodPattern;
}

Hope this helps others