-->

Changing the phase of a pattern image

2020-07-22 18:21发布

问题:

iI'm using a pattern image as a background color for a UITableViewCell by

cell.backgroundColor = [UIColor colorWithPatternImage[UIImage imageNamed:@"image.png"]]

However, I would like the bottom of the pattern image to align with the bottom of the cell. By default, the top left corner of the image is aligned with the origin of the cell. The reason I need this is because the cell's height is variable, but the bottom needs to appear the same regardless of the height.

The Apple docs specify that in order to change the phase of a pattern image, the color ([UIColor colorWothPatternImage]) should be made the current color, and then CGContextSetPatternPhase should be called. However, I am unsure of how to use this method in the context of setting the UITableViewCell's backgroundColor in cellForRowAtIndexPath.

I realize that this has been asked before, however it did not answer my question.

回答1:

I see that this question was asked a long time ago, and you probably have found a solution to it already, but I stumbled into the same problem and found a solution and figured I should post it for future reference. No sense in more than one person having a headache over the same thing :)

First you have to subclass whatever view you want the UIColor to be shifted in. So in this case, UITableViewCell.

..Lastly, use this code in the drawRect: method to shift the origin. And you're done!

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGSize phase = CGSizeMake(0, self.bounds.size.height); // CHANGE THESE VALUES TO WHATEVER X/Y SHIFT YOU NEED
CGContextSetPatternPhase(context, phase);

CGColorRef color = self.backgroundColor.CGColor;
CGContextSetFillColorWithColor(context, color);
CGContextFillRect(context, self.bounds);

CGContextRestoreGState(context);

The shift works by displacing the origin by the width and height values of 'phase'.

Hope that helps! (Don't forget [super drawRect:]!)