Better Programming

Advice for programmers.

Follow publication

Member-only story

The Shape Protocol and Custom Shapes in SwiftUI

Yong Cui
Better Programming
Published in
7 min readFeb 3, 2020

Photo by Paweł Czerwiński on Unsplash

Introduction

It’s been a trend for many years that in many apps, the user’s thumbnail is displayed as a circular image or a rectangular image with rounded corners. In the UIKit framework, when we use UIImageView, we can set the image view’s underlying layer’s cornerRadius to produce the needed thumbnails.

However, with the emerging popularity of SwiftUI framework, we find out that UIImageView isn’t part of the SwiftUI framework. We might wonder how we can make our images in the desired shapes without UIImageView.

In this piece, I’m going to show you how to create custom shapes in SwiftUI that can be applied to set the image’s outline shape. Before we dive in too deep, let’s first review what the SwiftUI’s Shape protocol is.

Shape Protocol

The Shape protocol was introduced as part of the SwiftUI framework. It is defined this way in the official documentation:

“A 2D shape that you can use when drawing a view.”

The Shape protocol provides a series of functions necessary for creating various two-dimensional shapes that can be used to configure views.

The above definition and the brief explanation may be too conceptual to understand. Don’t worry about it, as I bet that you’ll have a better understanding of this protocol and its usage by going through the remaining sections of this piece.

Built-in shapes

Let’s first take a look at the built-in shapes in the SwiftUI framework. As shown in the following figure, the SwiftUI framework has the Circle, RoundedRectangle, Rectangle, Capsule, and Ellipse shapes. The names of these shapes clearly indicate what they are.

Basic Shapes in SwiftUI

In addition to these shapes, by applying various transformation functions (e.g., offset, rotation), a few transformed shapes can be generated that also conform…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

No responses yet

Write a response