{"id":1562,"date":"2015-01-06T18:06:40","date_gmt":"2015-01-07T00:06:40","guid":{"rendered":"http:\/\/jamesonquave.com\/blog\/?p=1562"},"modified":"2015-01-06T18:40:39","modified_gmt":"2015-01-07T00:40:39","slug":"core-animation-swift-tutorial-animatable-properties","status":"publish","type":"post","link":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/","title":{"rendered":"Core Animation Swift Tutorial &#8211; Animatable Properties"},"content":{"rendered":"<p>This tutorial series requires a basic understanding of UIView hierarchy. If you are new to iOS development, you might want to begin with <a href=\"http:\/\/jamesonquave.com\/blog\/developing-ios-apps-using-swift-tutorial\/\">Developing iOS Apps Using Swift<\/a> first.<\/p>\n<p>When you first hear about Core Animation, you might think it is all about animation. However, animation is only a part of this framework. Core Animation is an infrastructure for compositing and manipulating visual content onscreen. It uses the GPU to accelerate the rendering of on-screen objects. It divides the content onscreen into individual objects called layers, and arranges them in a tree hierarchy (known as the layer tree). You are familiar with the UIView tree hierarchy, which is built upon the layer tree. In other words, Core Animation accounts for everything that you see onscreen.<\/p>\n<p>In the first part of this tutorial series, you are going to learn the basics of CALayer, how to use its properties to create neat visual effects easily, and at the end of this tutorial, you will learn the most important subclass of CALayer &#8211; <strong>CAShapeLayer<\/strong>.<\/p>\n<h2>What Is CALayer?<\/h2>\n<p><strong>CALayer<\/strong>s are rectangular objects that can contain visual content. They are stored into a tree hierarchy, and each manages the position of its children sublayers.<\/p>\n<p>Sound familiar? You may say, &#8220;It&#8217;s like UIView!&#8221; <\/p>\n<p>That&#8217;s true, but it&#8217;s not just a coincidence. Every <strong>UIView<\/strong> has a layer property known as the backing layer, which is an instance of <strong>CALayer<\/strong>. <strong>UIView<\/strong> just ensures the corresponding back layers are correctly connected in the layer tree when subviews are added or removed from the view. It is the backing layer that is responsible for display and animation of the view. The only major feature that the backing layer does not handle is user interaction.<\/p>\n<p>For the purposes of going through this tutorial, I recommend creating an empty single-view iPhone application.<\/p>\n<h2>Exploring CALayer<\/h2>\n<p>Creating a CALayer instance is very straightforward.<\/p>\n<pre class=\"brush:js;\">\r\nlet redLayer = CALayer()\r\n<\/pre>\n<p>We can set its <strong>frame<\/strong>, <strong>backgroundColor<\/strong>, and add it to a superlayer just like we do with UIView.<\/p>\n<pre class=\"brush:js;\">\r\nredLayer.frame = CGRect(x: 50, y: 50, width: 100, height: 100)\r\nredLayer.backgroundColor = UIColor.redColor().CGColor\r\nlayer.addSublayer(redLayer)\r\n<\/pre>\n<p>Add this code to a function called <strong>setup<\/strong> in the file ViewController.swift, and call the method from viewDidLoad. You should have something like this:<\/p>\n<pre class=\"brush: js;\">\r\nimport UIKit\r\n\r\nclass ViewController: UIViewController {\r\n    override func viewDidLoad() {\r\n        super.viewDidLoad()\r\n        \r\n        setup()\r\n    }\r\n    func setup() {\r\n        let redLayer = CALayer()\r\n        \r\n        redLayer.frame = CGRect(x: 50, y: 50, width: 50, height: 50)\r\n        redLayer.backgroundColor = UIColor.redColor().CGColor\r\n        self.view.layer.addSublayer(redLayer)\r\n    }\r\n}\r\n<\/pre>\n<p>Notice that the <strong>backgroundColor<\/strong> property of CALayer is a CGColor instead of UIColor.<\/p>\n<p>You can also set an image as the content via the <strong>contents<\/strong> property. <strong>contents<\/strong> is also known as backing image.<\/p>\n<p>We&#8217;ll use an image of a butterfly:<br \/>\n<br \/>\n<img decoding=\"async\" src=\"http:\/\/jamesonquave.com\/tutImg\/ButterflySmall.jpg\" \/><\/p>\n<p><i>Note that you&#8217;ll have to drag your image named ButterflySmall.jpg in to your Xcode project hierarchy in order for the UIImage() command to find the picture.<\/i><\/p>\n<pre class=\"brush:js;\">\r\nfunc setup() {\r\n    let redLayer = CALayer()\r\n    \r\n    redLayer.frame = CGRect(x: 50, y: 50, width: 50, height: 50)\r\n    redLayer.backgroundColor = UIColor.redColor().CGColor\r\n    self.view.layer.addSublayer(redLayer)\r\n    \r\n    \r\n    let imageLayer = CALayer()\r\n    let image = UIImage(named: \"ButterflySmall.jpg\")!\r\n    imageLayer.contents = image.CGImage\r\n    \r\n    imageLayer.frame = CGRect(x: 0, y: 100, width: image.size.width, height: image.size.height)\r\n    imageLayer.contentsGravity = kCAGravityResizeAspect\r\n    imageLayer.contentsScale = UIScreen.mainScreen().scale\r\n    \r\n    self.view.layer.addSublayer(imageLayer)\r\n}\r\n<\/pre>\n<p><strong>contentsGravity<\/strong> is a constant that specifies how the layer&#8217;s contents are positioned or scaled within its bounds.<\/p>\n<p><strong>contentsScale<\/strong> defines a ratio mapping between the size of the layer (measured in points) and the size of the bitmap used to present the layer\u2019s content (known as backing image, measured in pixels). The default value is 1.0. Normally we set the value as the scale of the image, as shown above. However, when working with image that are generated programmatically, or image that missing @2x\/@3x suffix, you will remember to manually set the layer&#8217;s <strong>contentsScale<\/strong>  to match the screen scale. Otherwise, you will get a pixelated image on your device.<\/p>\n<h2>Corners and Border<\/h2>\n<p><strong>CALayer<\/strong> has a property called <strong>cornerRadius<\/strong>, which applies rounded corners to the layer\u2019s background and border. When the <strong>masksToBounds<\/strong> property is set to true, the layer&#8217;s backing image and sublayers are clipped to this curve.<\/p>\n<p>On our redLayer, let&#8217;s apply some rounded corners, and make the border visible.<\/p>\n<pre class=\"brush:js;\">\r\nfunc setup() {\r\n    let redLayer = CALayer()\r\n    \r\n    redLayer.frame = CGRect(x: 50, y: 50, width: 50, height: 50)\r\n    redLayer.backgroundColor = UIColor.redColor().CGColor\r\n    \r\n    \/\/ Round corners\r\n    redLayer.cornerRadius = 25\r\n    \r\n    \/\/ Set border\r\n    redLayer.borderColor = UIColor.blackColor().CGColor\r\n    redLayer.borderWidth = 10\r\n    ...\r\n<\/pre>\n<p><strong>borderWidth<\/strong>, <strong>borderColor<\/strong> defines the width and color of a layer&#8217;s border.<\/p>\n<h2>Drop Shadow<\/h2>\n<p>There are four properties that you could configure the drop shadow for a layer, <strong>shadowOpacity<\/strong>, <strong>shadowColor<\/strong>, <strong>shadowOffset<\/strong> and <strong>shadowRadius <\/strong>. <strong>shadowRadius<\/strong> controls the blurriness of the shadow. A larger value could create a softer shadow that looks more natural.<\/p>\n<p>Let&#8217;s add a shadow to our redLayer as well.<\/p>\n<pre class=\"brush:js;\">\r\nredLayer.shadowColor = UIColor.blackColor().CGColor\r\nredLayer.shadowOpacity = 0.8\r\nredLayer.shadowOffset = CGSizeMake(2, 2)\r\nredLayer.shadowRadius = 3\r\n<\/pre>\n<p>Unlike the layer border, the layer&#8217;s shadow derives from the exact shape of its contents, not just the <strong>bounds<\/strong> and <strong>cornerRadius<\/strong>. However, if you know what the shape of your shadow would be in advance, you could specify it via <strong>shadowPath<\/strong> (an instance of CGPath). You could improve performance by doing this.<\/p>\n<h2>Animating Layers<\/h2>\n<p>Now that we&#8217;ve covered a few of the types of properties that are present in Core Animation, let&#8217;s quickly walk through creating some actual animations.<\/p>\n<pre class=\"brush: js;\">\r\n\/\/ Create a blank animation using the keyPath \"cornerRadius\", the property we want to animate\r\nlet animation = CABasicAnimation(keyPath: \"cornerRadius\")\r\n\r\n\/\/ Set the starting value\r\nanimation.fromValue = redLayer.cornerRadius\r\n\r\n\/\/ Set the completion value\r\nanimation.toValue = 0\r\n\r\n\/\/ How may times should the animation repeat?\r\nanimation.repeatCount = 1000\r\n\r\n\/\/ Finally, add the animation to the layer\r\nredLayer.addAnimation(animation, forKey: \"cornerRadius\")\r\n<\/pre>\n<p>Here we create a new <strong>CABasicAnimation<\/strong> for the <strong>cornerRadius<\/strong> property. Run your app and take a look, cool right?<\/p>\n<p>You could just as easily make this animation apply to any other animatable property of CALayer. Try swapping the &#8220;cornerRadius&#8221; keyPath value in the <strong>CABasicAnimation()<\/strong> constructor with the value &#8220;borderWidth&#8221;. What happens? What about a value of &#8220;shadowRadius&#8221;?<\/p>\n<p>From this tutorial you can see how the basics of Core Animation work. In the next part we&#8217;ll move on to learn about more animatable properties, and how to work with masks to do really nifty effects.<\/p>\n<p>Full code for this tutorial available <a href=\"https:\/\/github.com\/jquave\/CoreAnimationTutorial\/tree\/Part1\">here, on Github<\/a>.<\/p>\n<p>Want to get notified when the next part is out? Be sure to <a href=\"http:\/\/eepurl.com\/sDFL9\">subscribe to our newsletter here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial series requires a basic understanding of UIView hierarchy. If you are new to iOS development, you might want to begin with Developing iOS Apps Using Swift first. When you first hear about Core Animation, you might think it is all about animation. However, animation is only a part of this framework. Core Animation&#8230;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_links_to":"","_links_to_target":""},"categories":[50,26,10,32],"tags":[65,66,42],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Core Animation Swift Tutorial - Animatable Properties - Jameson Quave<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Core Animation Swift Tutorial - Animatable Properties - Jameson Quave\" \/>\n<meta property=\"og:description\" content=\"This tutorial series requires a basic understanding of UIView hierarchy. If you are new to iOS development, you might want to begin with Developing iOS Apps Using Swift first. When you first hear about Core Animation, you might think it is all about animation. However, animation is only a part of this framework. Core Animation...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/\" \/>\n<meta property=\"og:site_name\" content=\"Jameson Quave\" \/>\n<meta property=\"article:published_time\" content=\"2015-01-07T00:06:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-01-07T00:40:39+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/jamesonquave.com\/tutImg\/ButterflySmall.jpg\" \/>\n<meta name=\"author\" content=\"Guanshan Liu\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Guanshan Liu\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/\",\"url\":\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/\",\"name\":\"Core Animation Swift Tutorial - Animatable Properties - Jameson Quave\",\"isPartOf\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\"},\"datePublished\":\"2015-01-07T00:06:40+00:00\",\"dateModified\":\"2015-01-07T00:40:39+00:00\",\"author\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811\"},\"breadcrumb\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jamesonquave.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Core Animation Swift Tutorial &#8211; Animatable Properties\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\",\"url\":\"https:\/\/jamesonquave.com\/blog\/\",\"name\":\"Jameson Quave\",\"description\":\"Using computer technology to educate, and improve lives.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811\",\"name\":\"Guanshan Liu\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg\",\"caption\":\"Guanshan Liu\"},\"description\":\"Guanshan is an iOS Developer currently working as an iOS Engineer at Alibaba Inc. Before working at Alibaba, Guanshan worked with 2K Games on Civilization Revolution 1 and 2 for iOS. He has a Masters in Software Engineering from the University of York, UK as well as a Bachelors of Engineering in Information Security from Nanjing University of Aeronautics and Astronautics. Find him on twitter, @guanshanliu.\",\"sameAs\":[\"https:\/\/guanshanliu.github.io\"],\"url\":\"https:\/\/jamesonquave.com\/blog\/author\/guanshanliu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Core Animation Swift Tutorial - Animatable Properties - Jameson Quave","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/","og_locale":"en_US","og_type":"article","og_title":"Core Animation Swift Tutorial - Animatable Properties - Jameson Quave","og_description":"This tutorial series requires a basic understanding of UIView hierarchy. If you are new to iOS development, you might want to begin with Developing iOS Apps Using Swift first. When you first hear about Core Animation, you might think it is all about animation. However, animation is only a part of this framework. Core Animation...","og_url":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/","og_site_name":"Jameson Quave","article_published_time":"2015-01-07T00:06:40+00:00","article_modified_time":"2015-01-07T00:40:39+00:00","og_image":[{"url":"http:\/\/jamesonquave.com\/tutImg\/ButterflySmall.jpg"}],"author":"Guanshan Liu","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Guanshan Liu","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/","url":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/","name":"Core Animation Swift Tutorial - Animatable Properties - Jameson Quave","isPartOf":{"@id":"https:\/\/jamesonquave.com\/blog\/#website"},"datePublished":"2015-01-07T00:06:40+00:00","dateModified":"2015-01-07T00:40:39+00:00","author":{"@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811"},"breadcrumb":{"@id":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jamesonquave.com\/blog\/core-animation-swift-tutorial-animatable-properties\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jamesonquave.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Core Animation Swift Tutorial &#8211; Animatable Properties"}]},{"@type":"WebSite","@id":"https:\/\/jamesonquave.com\/blog\/#website","url":"https:\/\/jamesonquave.com\/blog\/","name":"Jameson Quave","description":"Using computer technology to educate, and improve lives.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/d0ef4e53cd95e21e389aefe6277f0811","name":"Guanshan Liu","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/8f00053e85112a67cee95968f2f36ab2?s=96&d=retro&r=pg","caption":"Guanshan Liu"},"description":"Guanshan is an iOS Developer currently working as an iOS Engineer at Alibaba Inc. Before working at Alibaba, Guanshan worked with 2K Games on Civilization Revolution 1 and 2 for iOS. He has a Masters in Software Engineering from the University of York, UK as well as a Bachelors of Engineering in Information Security from Nanjing University of Aeronautics and Astronautics. Find him on twitter, @guanshanliu.","sameAs":["https:\/\/guanshanliu.github.io"],"url":"https:\/\/jamesonquave.com\/blog\/author\/guanshanliu\/"}]}},"_links":{"self":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1562"}],"collection":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/comments?post=1562"}],"version-history":[{"count":19,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1562\/revisions"}],"predecessor-version":[{"id":1582,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1562\/revisions\/1582"}],"wp:attachment":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/media?parent=1562"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/categories?post=1562"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/tags?post=1562"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}