3

I want to make custom UIView with border. Here is my code:

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

And here is the result: enter image description here

All three UIView on this picture is my custom view, but only big UIView have the border. I don't understand why others have no border. What is wrong?

Maria
  • 755
  • 1
  • 11
  • 29

4 Answers4

3

You need local coordinates. Change

CGContextAddRect(context, self.frame);

to

CGContextAddRect(context, self.bounds);
Avt
  • 16,927
  • 4
  • 52
  • 72
  • If my answer solves the question, please accept it. Someone can find this post searching solution for similar issue. – Avt Mar 13 '14 at 08:57
0
  1. You didn't specify the classname for subviews

  2. why don't you try like this

    anyView.layer.borderColor = [UIColor redColor].CGColor;
    anyView.layer.borderWidth = 5.0f;
    
  3. Or add this method in your custom view

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

Yo have not added the path to your context

-(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);
}
Himanshu Joshi
  • 3,391
  • 1
  • 19
  • 32
  • CGContextAddRect draws without path http://www.techotopia.com/index.php/An_iOS_7_Graphics_Tutorial_using_Core_Graphics_and_Core_Image – Maria Mar 13 '14 at 08:47
  • I have provided the answer which I use generally. and you have missed the point `CGRect rectangle = CGRectMake(60,170,200,80);`. check that – Himanshu Joshi Mar 13 '14 at 08:49
  • I've used self.frame (should use self.bounds, but now it does not matter). So CGRectMake is needless. – Maria Mar 13 '14 at 10:01
  • You don't need call super in this method too stackoverflow.com/a/15387059/2803425 – Maria Mar 13 '14 at 10:02
0

Resolved! The problem was in self.frame for CGContextAddRect. It must be self.bounds to draw in my view.

Maria
  • 755
  • 1
  • 11
  • 29