Take the 2-minute tour ×

I need to draw a rect filled with color and its border... the rect is filled with color properly but the outside border is partially drawn, just the right side of the rect is drawn!

The generated UIImage is going to be used in a UITableViewCell's imageView.

- (UIImage *)legendItemWithColor:(UIColor *)color
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect outside = CGRectMake(128, 128, 128, 128);
    CGRect legend = CGRectInset(outside, 1, 1);

    NSLog(@"Outside: %@", NSStringFromCGRect(outside));
    NSLog(@"Legend: %@", NSStringFromCGRect(legend));

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, legend);

    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextStrokeRect(context, outside);

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    return img;
share|improve this question
i checked your code on simulator and it's fine. That said I think the issue might be related with the Context bounds which is`self.view.frame.size` –  Michał Zygar Dec 5 '11 at 15:26
can you try to use it in a tableview with cell.imageView.image = [self legendItemWithColor:[UIColor orangeColor]]; –  Progeny Dec 5 '11 at 15:28
it's not fine then. However to fix it you have to pass proper CGSize to UIGraphicsBeginImageContext() not the self.view.frame.size. I'd suggest to pass only the size you need so, i.e. CGSizeMake(128+128+2,128+128+2). Then it displays ok –  Michał Zygar Dec 5 '11 at 15:40
Thanks, now it's working fine! –  Progeny Dec 5 '11 at 15:56
@Michal Zygar - looks like you solved it. Recommend posting as an answer. –  Jacob Jennings Dec 5 '11 at 18:20
add comment

1 Answer

up vote 2 down vote accepted

The problem is when you pass self.view.frame.size to UIGraphicsBeginImageContext() and then use drawn rectangle in array, it is downscaled and the border is obfuscated. Try to pass only the size you need so, i.e. CGSizeMake(2*128+128+2,2*128+128+2). Then it displays ok

share|improve this answer
add comment

Your Answer


