2014-03-13 136 views
2

我想用边框制作自定义UIView。这里是我的代码:UIView drawRect问题

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 4.0); 
    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]); 
    CGContextAddRect(context, self.frame); 
    CGContextStrokePath(context); 
} 

,这里是结果:enter image description here

所有这三个UIView的这张图片上是我的自定义视图,但只有大的UIView有边界。我不明白为什么其他人没有边界。哪里不对?

+0

所有'UIView'都是相同的自定义类吗? –

+0

请显示一些代码? –

+0

我通过故事板制作。我没有更多的代码,只是用这个drawRect方法的自定义类 – Maria

回答

2

您需要本地坐标。更改

CGContextAddRect(context, self.frame); 

CGContextAddRect(context, self.bounds); 
+0

是的,我刚刚意识到这一点。但无论如何,谢谢! – Maria

+0

如果我的答案解决了这个问题,请接受它。有人可以找到这个搜索解决方案的类似问题。 – Avt

0
  1. 你没有指定子视图

  2. 类名,为什么不试试这样

    anyView.layer.borderColor = [UIColor redColor].CGColor; 
    anyView.layer.borderWidth = 5.0f; 
    
  3. 或者在您的自定义视图中添加这种方法

    -(void)awakeFromNib{ 
    
        [super awakeFromNib]; 
    
        self.layer.borderColor = [UIColor redColor].CGColor; 
        self.layer.borderWidth = 5.0f; 
    
    } 
    
+0

你是什么意思 - 你没有指定子视图的类名? 我将它命名为BorderedView并为故事板中的所有UIView指定类名称。 – Maria

+0

感谢2和3,但我还需要使边界不完整 - 例如没有上边界。 – Maria

+0

在视图顶部添加白色的普通视图,如果需要,它将隐藏该边框 –

0

Y o尚未将path添加到您的上下文中

-(void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGPathRef path = CGPathCreateWithRect(rect, NULL); 
    [[UIColor blueColor] setStroke]; 
    CGContextSetLineWidth(context, 4.0); 
    CGContextAddPath(context, path); 
    CGContextDrawPath(context, kCGPathFillStroke); 
    CGPathRelease(path); 
} 
+0

CGContextAddRect绘制无路径http://www.techotopia.com/index.php/An_iOS_7_Graphics_Tutorial_using_Core_Graphics_and_Core_Image – Maria

+0

我已经提供了我一般使用的答案。并且你错过了'CGRect rectangle = CGRectMake(60,170,200,80)''点。检查 –

+0

我已经使用self.frame(应使用self.bounds,但现在没关系)。所以CGRectMake是不必要的。 – Maria

0

解决! 问题出在CGContextAddRect的self.frame中。它必须是self.bounds来绘制我的视图。