CGContextStrokeRect未出现在视图中

时间:2014-12-03 19:25:34

标签: ios objective-c core-graphics

我正在尝试绘制一个带边框的彩色矩形(如果已选中),但我似乎无法让边框绘制。彩色矩形显示在正确的位置和颜色,但边框永远不会显示。我试图缩小矩形以查看它是否在某种程度上在视图外部剪裁,但这也不起作用。

我在StackOverflow上环顾四周,但似乎没有任何与此相关的问题(唯一的候选人是this one,但它处理图像,所以我认为它不能帮助我)。

以下代码的一些解释:

  • _card是一个属性,其中包含有关卡的一些信息,用于确定如何绘制
  • 我知道if语句中的代码正在执行,因为NSLog出现在控制台中

这是我正在讨论的视图中的drawRect方法(_card.isSelected中的代码if语句是我认为应该生成边框的代码):

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    if ([_card isKindOfClass:[NSNumber class]] && [_card intValue] == -1) {
        NSLog(@"No card");
    } else if ([_card isKindOfClass:[Card class]]) {
        Card *card = _card;

        if (card.shouldAnimate) {
            [self fadeSelfIn];
        }

        if ([_card isKindOfClass:[WeaponCard class]]) {
            CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
        } else if ([_card isKindOfClass:[ArmorCard class]]) {
            CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
        }

        if (card.isSelected)
            CGContextSetStrokeColorWithColor(context, [UIColor purpleColor].CGColor);
            CGContextStrokeRect(context, self.bounds);
            NSLog(@"Drawing border on selected card with bounds %@, NSStringFromCGRect(self.bounds));
        }

        CGContextFillRect(context, self.bounds);
    }

}

1 个答案:

答案 0 :(得分:2)

您对CGContextFillRect的来电正在描绘您的中风线。首先填写,然后填写:

CGContextFillRect(context, self.bounds);

if (card.isSelected) {
    CGContextSetStrokeColorWithColor(context, [UIColor purpleColor].CGColor);

    // As rob mayoff points out in the comments, it's probably a good idea to inset
    // the stroke rect by half a point so the stroke is not getting cut off by
    // the view's border, which is why you see CGRectInset being used here.
    CGContextStrokeRect(context, CGRectInset(self.bounds, 0.5, 0.5));
}
相关问题