Getting started with iOSUILabelChange Status Bar ColorPassing Data between View ControllersManaging the KeyboardUIButtonUILocalNotificationUIImageViewChecking for Network ConnectivityAccessibilityUITableViewAuto LayoutUIViewUIAlertControllerMKMapViewUIColorNSAttributedStringCAAnimationUITextViewUINavigationControllerConcurrencyCAGradientLayerUIGestureRecognizerCustom UIViews from XIB filesSafari ServicesUIStackViewUIImageUIWebViewCALayeriOS - Implementation of XMPP with Robbie Hanson frameworkSwift and Objective-C interoperabilityNSDateCustom fontsAVSpeechSynthesizerUIBarButtonItemUIScrollViewLocalizationNSNotificationCenterUITextFieldAlamofireUIViewControlleriBeaconCLLocationNSURLSessionUISwitchChecking iOS versionUniversal LinksUICollectionViewPDF Creation in iOSIn-App PurchaseNSTimerCGContext ReferenceUITabBarControllerUISearchControllerUIActivityViewControllerCore LocationFacebookSDKAFNetworkingCTCallCenterUIImagePickerControllerNSUserDefaultsUIControl - Event Handling with BlocksUIBezierPathUIPageViewControllerUIAppearancePush NotificationsKey Value Coding-Key Value ObservationInitialization idiomsStoryboardBackground Modes and EventsFastlaneCAShapeLayerWKWebViewUUID (Universally Unique Identifier)CategoriesHandling URL SchemesRealmARC (Automatic Reference Counting)UIPickerViewDynamic TypeNSURLSWRevealViewControllerSnapshot of UIViewDispatchGroupGCD (Grand Central Dispatch)Size Classes and AdaptivityUIScrollView AutoLayoutIBOutletsAWS SDKDebugging CrashesUISplitViewControllerUISplitViewControllerUIDeviceCloudKitGameplayKitXcode Build & Archive From Command LineXCTest framework - Unit TestingNSDataAVPlayer and AVPlayerViewControllerDeep Linking in iOSApp Transport Security (ATS)Core GraphicsSeguesUIDatePickerNSPredicateEventKitNSBundleSiriKitContacts FrameworkDynamically updating a UIStackViewiOS 10 Speech Recognition APINSURLConnectionStoreKitCode signingCreate .ipa File to upload on appstore with ApplicationloaderResizing UIImageSize Classes and AdaptivityMKDistanceFormatter3D TouchGameCenter LeaderboardsKeychainHandle Multiple Environment using MacroSet View BackgroundBlockContent Hugging/Content Compression in AutolayoutiOS Google Places APINavigation BarUITextField DelegateApp wide operationsUILabel text underliningCut a UIImage into a circleMake selective UIView corners roundedConvert HTML to NSAttributed string and vice verseConvert NSAttributedString to UIImageCoreImage FiltersFace Detection Using CoreImage/OpenCVMPMediaPickerDelegateGraph (Coreplot)NSHTTPCookieStorageFCM Messaging in SwiftCreate a Custom framework in iOSCustom KeyboardAirDropSLComposeViewControllerAirPrint tutorial in iOSUISliderCarthage iOS SetupHealthkitCore SpotLight in iOSUI TestingCore MotionQR Code Scannerplist iOSNSInvocationUIRefreshControl TableViewWCSessionDelegateAppDelegateApp Submission ProcessMVVMUIStoryboardBasic text file I/OiOS TTSMPVolumeViewObjective-C Associated ObjectsPassing Data between View Controllers (with MessageBox-Concept)UIPheonix - easy, flexible, dynamic & highly scalable UI frameworkChain Blocks in a Queue (with MKBlockQueue)SimulatorBackground ModesNSArrayOpenGLUIScrollView with StackView childCache online imagesMVP ArchitectureUIKit DynamicsConfigure Beacons with CoreBluetoothCore DataExtension for rich Push Notification - iOS 10.Profile with InstrumentsApplication rating/review requestMyLayoutUIFontSimulator BuildsSimulating Location Using GPX files iOSCustom methods of selection of UITableViewCellsCustom methods of selection of UITableViewCellsUISegmentedControlSqlCipher integrationCustom UITextFieldSecurityGuideline to choose best iOS Architecture PatternsUIFeedbackGeneratorUIKit Dynamics with UICollectionViewMulticast DelegatesUsing Image AseetsUITableViewCellRuntime in Objective-CModelPresentationStylesCydiaSubstrate tweakCreate a video from imagesCodableFileHandleNSUserActivityRich NotificationsLoad images asyncADDING A SWIFT BRIDGING HEADERCreating an App IDSwift: Changing the rootViewController in AppDelegate to present main or login/onboarding flowattributedText in UILabelUITableViewController

CAGradientLayer

Other topics

Remarks:

  • Use startPoint and endPoint to change the orientation of the CAGradientLayer.
  • Use the locations to affect the spread/positions of the colors.

Creating a CAGradientLayer

// View to hold the CAGradientLayer.
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
    
// Initialize gradient layer.
let gradientLayer: CAGradientLayer = CAGradientLayer()
    
// Set frame of gradient layer.
gradientLayer.frame = view.bounds
   
// Color at the top of the gradient.
let topColor: CGColor = UIColor.red.cgColor
    
// Color at the bottom of the gradient.
let bottomColor: CGColor = UIColor.yellow.cgColor
    
// Set colors.
gradientLayer.colors = [topColor, bottomColor]
    
// Set locations of the colors.
gradientLayer.locations = [0.0, 1.0]
    
// Insert gradient layer into view's layer heirarchy.
view.layer.insertSublayer(gradientLayer, at: 0)

Result :

Simple CAGradientLayer.

Creating a CGGradientLayer with multiple colors.

// View to hold the CAGradientLayer.
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
    
// Initialize gradient layer.
let gradientLayer: CAGradientLayer = CAGradientLayer()
    
// Set frame of gradient layer.
gradientLayer.frame = view.bounds
    
// Color at the top of the gradient.
let topColor: CGColor = UIColor.blue.cgColor
    
// Color at the middle of the gradient.
let middleColor: CGColor = UIColor.yellow.cgColor
    
// Color at the bottom of the gradient.
let bottomColor: CGColor = UIColor.green.cgColor
    
// Set colors.
gradientLayer.colors = [topColor, middleColor, bottomColor]
    
// Set locations of the colors.
gradientLayer.locations = [0.0, 0.5, 1.0]
    
// Insert gradient layer into view's layer heirarchy.
view.layer.insertSublayer(gradientLayer, at: 0)

Result :

Complex CAGradientLayer.

Creating a horizontal CAGradientLayer.

// View to hold the CAGradientLayer.
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))

// Initialize gradient layer.
let gradientLayer: CAGradientLayer = CAGradientLayer()

// Set frame of gradient layer.
gradientLayer.frame = view.bounds

// Color at the top of the gradient.
let topColor: CGColor = UIColor.redColor().CGColor

// Color at the bottom of the gradient.
let bottomColor: CGColor = UIColor.yellowColor().CGColor

// Set colors.
gradientLayer.colors = [topColor, bottomColor]

// Set start point.
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)

// Set end point.
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

// Insert gradient layer into view's layer heirarchy.
view.layer.insertSublayer(gradientLayer, atIndex: 0)

Result :

Horizontal CAGradientLayer.

Creating a horizontal CAGradientLayer with multiple colors.

// View to hold the CAGradientLayer.
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))

// Initialize gradient layer.
let gradientLayer: CAGradientLayer = CAGradientLayer()

// Set frame of gradient layer.
gradientLayer.frame = view.bounds

// Color at the top of the gradient.
let topColor: CGColor = UIColor.greenColor().CGColor

// Color at the middle of the gradient.
let middleColor: CGColor = UIColor.blueColor().CGColor

// Color at the bottom of the gradient.
let bottomColor: CGColor = UIColor.blackColor().CGColor

// Set colors.
gradientLayer.colors = [topColor, middleColor, bottomColor]

// Set start point.
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)

// Set end point.
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

// Insert gradient layer into view's layer heirarchy.
view.layer.insertSublayer(gradientLayer, atIndex: 0)

Result :

enter image description here

Animating a color change in CAGradientLayer.

// Get the current colors of the gradient.
let oldColors = self.gradientLayer.colors
    
// Define the new colors for the gradient.
let newColors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
    
// Set the new colors of the gradient.
self.gradientLayer.colors = newColors
    
// Initialize new animation for changing the colors of the gradient.
let animation: CABasicAnimation = CABasicAnimation(keyPath: "colors")
    
// Set current color value.
animation.fromValue = oldColors
    
// Set new color value.
animation.toValue = newColors
   
// Set duration of animation.
animation.duration = 0.3
    
// Set animation to remove once its completed.
animation.isRemovedOnCompletion = true
    
// Set receiver to remain visible in its final state when the animation is completed.
animation.fillMode = kCAFillModeForwards
    
// Set linear pacing, which causes an animation to occur evenly over its duration.
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    
// Set delegate of animation.
animation.delegate = self
    
// Add the animation.
self.gradientLayer.addAnimation(animation, forKey: "animateGradientColorChange")

Result :

Basic CAGradientLayer color change animation.

Syntax:

  • CAGradientLayer() // Returns an initialized CALayer object.
  • CAGradientLayer(layer: layer) // Override to copy or initialize custom fields of the specified layer.

Parameters:

ParameterDetails
colorAn array of CGColorRef objects defining the color of each gradient stop. Animatable.
locationsAn optional array of NSNumber objects defining the location of each gradient stop. Animatable.
endPointThe end point of the gradient when drawn in the layer’s coordinate space. Animatable.
startPointThe start point of the gradient when drawn in the layer’s coordinate space. Animatable.
typeStyle of gradient drawn by the layer. Defaults to kCAGradientLayerAxial.

Contributors

Topic Id: 1190

Example Ids: 3856,4227,4228,4229,12652

This site is not affiliated with any of the contributors.