Progeny
Progeny

Reputation: 692

CGContextStrokeRect is drawing only a side of rect

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
{
    UIGraphicsBeginImageContext(self.view.frame.size);
    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();
    UIGraphicsEndImageContext();
    UIGraphicsPopContext();

    return img;
}

Upvotes: 3

Views: 1880

Answers (1)

Michał Zygar
Michał Zygar

Reputation: 4092

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

Upvotes: 2

Related Questions