Search code examples
swiftuiviewcalayer

Swift - How to create a view with a shape cropped in it


I'm trying to achieve the result shown in the image using swift 1.2 and xcode 6.

Basically I want to create a view with a shape cut in it to be able to see the the view below to make a tutorial for my app. I know how to create a circular shape but i don't know how to cut it out in a view. I need a complete example on how to do it please. Thanks in advance

Image


Solution

  • The easiest way to do this would be to create a png image with partly transparent white around the outside and a clear circle in the middle. Then stack 2 image views on top of each other, with the masking image on top, and set its "opaque" flag to false.

    You could also do this by creating a CAShapeLayer and set it up to use a translucent white color, then install a shape that is the square with the hole cut out of it shape. You'd install that shape layer on top of your image view's layer.

    The most general-purpose way to do that would be to create a custom subclass of UIImageView and have the init method of your subclass create and install the shape layer. I just created a gist yesterday that illustrated creating a custom subclass of UIImageView. Here is the link: ImageViewWithGradient gist

    That gist creates a gradient layer. It would be a simple matter to adapt it to create a shape layer instead, and if you modified the layoutSubviews method you could make it adapt the view and path if the image view gets resized.

    EDIT:

    Ok, I took the extra step of creating a playground that creates a cropping image view. You can find that at ImageViewWithMask on github

    The resulting image for my playground looks like this:

    Image with circular mask