【问题标题】:CGContextStrokeRect is drawing only a side of rectCGContextStrokeRect 仅绘制矩形的一侧
【发布时间】:2011-12-05 13:59:07
【问题描述】:

我需要绘制一个填充颜色的矩形及其边框... 矩形已正确填充颜色,但部分绘制了外部边框,仅绘制了矩形的右侧!

生成的 UIImage 将用于 UITableViewCell 的 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;
}

【问题讨论】:

  • 我在模拟器上检查了你的代码,没问题。也就是说我认为这个问题可能与上下文边界有关,即self.view.frame.size
  • 你可以尝试在tableview中使用cell.imageView.image = [self legendItemWithColor:[UIColor orangeColor]];
  • 那就不行了。但是要修复它,您必须将正确的 CGSize 传递给 UIGraphicsBeginImageContext() 而不是 self.view.frame.size。我建议只传递你需要的大小,即 CGSizeMake(128+128+2,128+128+2)。然后显示ok
  • 谢谢,现在一切正常!
  • @Michal Zygar - 看起来你解决了它。建议发布作为答案。

标签: iphone objective-c ios sdk core-graphics


【解决方案1】:

问题是当你将 self.view.frame.size 传递给 UIGraphicsBeginImageContext() 然后在数组中使用绘制的矩形时,它被缩小并且边框被混淆了。尝试只传递您需要的大小,即 CGSizeMake(2*128+128+2,2*128+128+2)。然后就显示ok了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多