Search This Blog

Showing posts with label CALayer. Show all posts
Showing posts with label CALayer. Show all posts

Saturday, September 23, 2017

iOS CALayer and how to use it


Description

Every UIView has CALayer. Visual representation of UIView is defined by attributes of CALayer property. You can setup many visual attributes of the view through the CALayer property: 
  • rounded corners
  • borders
  • opacity
  • background color
  • image content
  • shadows
  • and others
So, UIView wraps CALayer and all visual changes that you send to UIView get forward to CALayer object. UIView has one root CALayer and this root layer can contain sublayers. 

Code 

Rounded Corners
// make rounded corners
self.customView.layer.cornerRadius = 16

Borders
// add borders
self.customView.layer.borderColor = UIColor.black.cgColor
self.customView.layer.borderWidth = 3

Shadows
// add shadows
self.customView.layer.shadowOffset = CGSize(width: 6, height: 6)
self.customView.layer.shadowOpacity = 0.8
self.customView.layer.shadowRadius = 6
self.customView.layer.shadowColor = UIColor.black.cgColor

Image content
// add image content
self.customView.layer.contents = UIImage(named: "cats-eyes")?.cgImage
self.customView.layer.contentsGravity = kCAGravityResizeAspectFill
self.customView.layer.masksToBounds = true

Opacity
// opacity background
self.customView.layer.backgroundColor = UIColor.red.cgColor
self.customView.layer.opacity = 0.5

Screens



CALayer Demo project on GitHub