2014-12-03 50 views
1

我想绘制一个带边框的彩色矩形,如果它被选中,但我似乎无法得到边界绘制。彩色矩形显示在正确的位置和颜色上,但边框从不出现。我试图缩小比例尺来查看它是否以某种方式在视图的外部裁剪,但那也不起作用。CGContextStrokeRect没有出现在视图中

我环顾了一下StackOverflow,但似乎没有任何与此相关的问题(唯一的候选人是this one,但它涉及图像,所以我不认为它可以帮助我)。

  • _card是保存有关使用该卡的一些信息来确定如何绘制
  • 我知道在代码if语句是一个属性:

    下面的代码的几点说明执行,因为NSLog的出现在控制台

这里是我讲的观点我的drawRect方法(在_card.isSelected的代码,如果语句是什么,我相信应该产生的边界):

- (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); 
    } 

} 

回答

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)); 
} 
+0

你可能也想你的插图界矩形:'CGContextStrokeRect(背景下,CGRectInset(self.bounds,0.5,0.5));'。 – 2014-12-03 19:48:00

+0

如果我不插入矩形,边框是否会被剪切到视图之外? – hhanesand 2014-12-03 19:51:35

+0

是的,笔划线的中间将位于视图的边界上,使线在视图的一半内,半在外(由于它在视图的范围之外,因此不会被绘制)。将它插入半个点可能是一个好主意。 – TylerTheCompiler 2014-12-03 20:00:11