Monday, 31 December 2018

Custom Loading Indicator - Create dots graphic view by code

Check source code at Github:
https://github.com/Sylvia-YiyinShen/LoadingIndicatorDemo


This 2 mins tutorial covers the key things to create a graphic view as below by code


Draw a filled circle

UIBezierPath provides two init functions to draw a circle. The first one will draw a circle fitting in rect, while the second one is more customisable and allows to draw a pie within the circle. We will pick the second one since we want to draw circles at different positions.

  • convenience init(ovalIn rect: CGRect)
  • convenience init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool)
Just try to call the function inside draw(_ rect: CGRect)





Draw dots in a circle

The remaining task is just calculating the eight CGPoint for all the dots. 
For each dot, apply: CGPoint(x: x0 + cos(angle) * radius, y: y0 + radius * sin(angle))

  • (x0, y0) is the centre of the view
  • radius is the radius of the circle which the dots making up
  • angle 0 ~ pi * 2
Note: Using centerXAnchor and centerYAnchor is wrong, since those indicates the position in parent. We have to calculate the centre of UIView itself, so use bounds to calculate instead
Example solution




No comments:

Post a Comment