UIView drawRect问题

3

我想创建一个带边框的自定义UIView。这是我的代码:

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

这是结果:在这里输入图片描述 这张图片上的三个 UIView 都是我的自定义视图,但只有大的 UIView 有边框。我不明白为什么其他的没有边框。出了什么问题?

所有的 UIView 都是同一个自定义类吗? - Himanshu Joshi
请展示一些代码? - Himanshu Joshi
我是通过Storyboard来实现的。我没有更多的代码,只有一个带有drawRect方法的自定义类。 - Maria
不知道发生了什么,但你错过了[super drawRect:rect]; - Mani
Mani,http://stackoverflow.com/a/15387059/2803425 - Maria
4个回答

3
你需要本地坐标。更改为:
CGContextAddRect(context, self.frame);

为了

CGContextAddRect(context, self.bounds);

如果我的回答解决了问题,请接受它。有人可能会在寻找类似问题的解决方案时找到这篇帖子。 - 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;
    
    }
    

你的意思是 - 你没有为子视图指定类名? 我将其命名为BorderedView,并在storyboard中为所有UIView指定了类名。 - Maria
谢谢你提供的2和3,但我还需要制作非完整边框 - 比如没有上边线。 - Maria
在你的视图顶部添加一个白色的纯视图,如果需要,它将隐藏边框。 - Vijay-Apple-Dev.blogspot.com
这将是tableViewCell,而不仅仅是视图。所以那不是正确的方法。 - Maria

0

你还没有将 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);
}

CGContextAddRect在没有路径的情况下绘制 http://www.techotopia.com/index.php/使用Core_Graphics和Core_Image进行iOS_7图形教程 - Maria
我已经提供了我通常使用的答案,而你却没有抓住重点CGRect rectangle = CGRectMake(60,170,200,80);。请检查一下。 - Himanshu Joshi
我使用了self.frame(应该使用self.bounds,但现在无所谓)。因此CGRectMake是不必要的。 - Maria
在这个方法中,你不需要调用super。stackoverflow.com/a/15387059/2803425 - Maria

0

问题已解决! CGContextAddRect 中的问题在于 self.frame。必须使用 self.bounds 才能在我的视图中绘制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接