How to change pattern phase when using [UIColor colorWithPatternImage:]?
I'm using [UIColor colorWithPatternImage:]
to set the background image for my grouped UITableViewCell. I got free rounded-corner for my cells and everything looks great, until I try to give the cell a different height.
Ideally, I want the background image to be vertically-centered, but the colorWithPatternImage:
method starts the image pattern from the lower-left corner, which make my cell looks bad.
It says in the documentation that
"By default, the phase of the returned color is 0, which causes the top-left corner of the image to be aligned with the drawing origin. To change the phase, make the color the current color and then use the CGContextSetPatternPhase function to change the phase."
But I have no idea how to use CGContextSetPatternPhase
with my current implementation.
I tried
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGSize phase = CGSizeMake(50, 50);
CGContextSetPatternPhase(context, phase);
UIImage* image = [UIImage imageNamed:@"cell_background"];
UIColor* color = [UIColor colorWithPatternIma开发者_开发知识库ge:image];
self.backgroundColor = color;
CGContextRestoreGState(context);
[super drawRect:rect];
}
But that doesn't have any effect on the pattern phase. Can anyone tell me how am I suppose to use it?
Many thanks,
Joseph
Core Graphics calls are generally used as part of a specific drawing process; setting the backgroundColor
property doesn’t actually draw anything, it just sets how a view draws itself by default. The Quartz 2D Programming Guide has an explanation of how to draw using pattern images; you might be able to take a shortcut via
CGColorRef color = [UIColor colorWithPatternImage:image].CGColor;
CGContextSetFillColorWithColor(context, color);
CGContextFillRect(context, self.bounds);
…but I wouldn’t guarantee it, because UIColor patterns may not play well with Core Graphics. You might have to take the more elaborate route described in the link above.
精彩评论