TUTORIAL: Draw a nice triangle view with a border using CAShapeLayer

Drawing a custom-shaped background view with a CAShapeLayer is an easy way, how to decorate the app and make its titles or headers more distinguished.

The demo app

The demo app for this tutorial contains only one view with a background image, a label and its background view.

iOS Simulator Screen Shot 24 Aug 2014 15.08.48


Complete code

You can find the complete code here (tested with Xcode 6 beta 6):

Gettings started

Open Xcode and Create a new project by choosing the Single View Application template. If you’re using XCode 6, choose whether Swift or Objective-C on the screen. This tutorial covers both Swift and Objective-C.

Screen Shot 2014-08-24 at 15.18.07


User interface

Open the Main.storyboard file. Drag a new imageview to the main view.

Screen Shot 2014-08-24 at 15.22.39

Now add a header background view. Setup its position and height constraints.

Screen Shot 2014-08-24 at 15.23.28

Let’s now add a header label. Setup its position and height constraints.

Screen Shot 2014-08-24 at 15.23.40

Setup an “equal width constraint” for the header label and its background view. Set the multiplier to 1.35 – the background view will be slightly bigger than the label.

Screen Shot 2014-08-24 at 15.24.44

Set the custom class of the background view to the TriangleView.

Screen Shot 2014-08-24 at 15.29.58

TriangleView class

Now create the TriangleView class and override the drawRect method of UIView.

In the drawRect method we will create two CAShapeLayers – one to mask the view’s layer (to achieve the custom shape) and another to draw the white border around the shape.


Let’s start with the first CAShapeLayer – create it and set its frame to match our view’s bounds:



Now it’s time to create the custom shaped path. We’ll start at the 0-point and move back to it with a small offset:

iOS Simulator Screen Shot 24 Aug 2014 17.38.41



Note, that it is not needed to call CGPathRelease in Swift, because Core Foundation objects are automatically memory-mapped by Swift.

The last thing is to set the layer’s mask to the newly created shapelayer:



To create the border layer, the same path will be used. The only difference is that the border shape will have a transparent fillColor and a white strokeColor.



And the full source code is here:

Tested with Xcode 6 beta 6.

  1. Mahmoud Awwad
  2. Shashikanr More
  3. Sheev Palpatin

Leave a Reply

Your email address will not be published. Required fields are marked *