objective-ciosmacosnsviewnsgradient

Drawing borders and highlights natively in Cocoa


How can I draw highlights and non-4-sided borders natively in Cocoa?

An example is the image below. There's a small 1px white inner border on the top and a grey 1px inner border on the bottom. There's also a dark gray border only on the top and the bottom of the view.

Can this be done natively? Or does this require images?

enter image description here


Solution

  • A quick way to get an inner border is to use the layer's shadow properties from the view you want bordered (note the -1, which places the border inside the edge):

    myView.layer.shadowOpacity = 1.0;
    myView.layer.shadowColor = [UIColor blackColor].CGColor;
    myView.layer.shadowOffset = CGSizeMake( 0, -1 );
    

    Otherwise you can subclass the view and put something like this in your drawRect: method:

    [super drawRect: rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState( context );
    CGContextSetStrokeColorWithColor( context, [UIColor blackColor].CGColor );
    CGContextSetLineWidth( context,  1.0 );
    
    CGContextMoveToPoint( context, 0, 0 );
    
    CGContextAddLineToPoint( context,  self.bounds.size.width, 0 );
    CGContextStrokePath( context );        
    
    CGContextRestoreGState( context );