Friday, 3 June 2016

Add dashed border around a UIView

Hello.., some time we have some specific need in our . We may want a UIView to have a dashed border . We can add a border to UIView  , but that will be solid . To add a simple border, we do this:

  view.layer.borderWidth = 1
 view.layer.borderColor  = UIColor.lightGrayColor().CGColor


But what if we want to add dashed border like this:

   

To add dashed border like this , we can create a new layer and that layer as sublayer of the required view.



func dashedBorderLayerWithColor(color:CGColorRef) -> CAShapeLayer {
        
       let  borderLayer = CAShapeLayer()
        borderLayer.name  = "borderLayer"
         let frameSize = selectedViewForImage.frame.size
        let shapeRect = CGRectMake(0, 0, frameSize.width, frameSize.height)
        
        borderLayer.bounds=shapeRect
        borderLayer.position = CGPointMake( frameSize.width/2,frameSize.height/2)
        borderLayer.fillColor = UIColor.clearColor().CGColor
        borderLayer.strokeColor = color
        borderLayer.lineWidth=1
        borderLayer.lineJoin=kCALineJoinRound
        borderLayer.lineDashPattern = NSArray(array: [NSNumber(integer: 8),NSNumber(integer:4)]) as? [NSNumber]
        
        let path = UIBezierPath.init(roundedRect: shapeRect, cornerRadius: 0)
        
        borderLayer.path = path.CGPath
        
        return borderLayer

    }

Here we create an instance of CAShapeLayer. Then set its frame. After that we have set the different properties on instance of CALayer like fill color and stroke color and line width. Since we add a dashed line so we set lineJoin property to KCALineJoinRound. 
Then define the lineDashPattern which takes an array of numbers.
Then finally create a Bezierpath and set that path to the layer. and then return the layer.

Now to add dashed layer we can call above defined function to get the dashed layer like this

let borderLayer  = dashedBorderLayerWithColor(UIColor.blackColor().CGColor)
        
view.layer.addSublayer(borderLayer)
        

2 comments: