SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  GradientBorderedView.swift
  3. //  DiaryOfBloodPressure
  4. //
  5. //  Created by Aleksandr Smetannikov on 04/10/2019.
  6. //  Copyright © 2019 AlexSmetannikov. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. class GradientBorderedView: UIView {
  12.     private var gradientLayer = CAGradientLayer()
  13.     private var borderLayer = CAShapeLayer()
  14.  
  15.     var colors: [UIColor] = []
  16.  
  17.     var borderWidth: CGFloat = 1 {
  18.         didSet {
  19.             setNeedsDisplay()
  20.         }
  21.     }
  22.  
  23.     var cornerRadius: CGFloat = 4 {
  24.         didSet {
  25.             layer.cornerRadius = cornerRadius
  26.             setNeedsDisplay()
  27.         }
  28.     }
  29.  
  30.     override var frame: CGRect {
  31.         didSet {
  32.             setNeedsDisplay()
  33.         }
  34.     }
  35.  
  36.     required init?(coder: NSCoder) {
  37.         super.init(coder: coder)
  38.  
  39.         layer.addSublayer(gradientLayer)
  40.     }
  41.  
  42.     override init(frame: CGRect) {
  43.         super.init(frame: frame)
  44.  
  45.         layer.addSublayer(gradientLayer)
  46.     }
  47.  
  48.     override func draw(_ rect: CGRect) {
  49.         makeGradietBorder()
  50.  
  51.         super.draw(rect)
  52.     }
  53.  
  54.     private func makeGradietBorder() {
  55.         gradientLayer.transform = CATransform3DMakeRotation( -CGFloat.pi / 2, 0, 0, 1)
  56.         gradientLayer.frame = CGRect(origin: .zero, size: frame.size)
  57.         gradientLayer.colors = colors.isEmpty ? [] : colors.map { $0.cgColor }
  58.  
  59.         borderLayer.borderWidth = borderWidth
  60.         borderLayer.cornerRadius = cornerRadius
  61.         borderLayer.path = UIBezierPath(rect: gradientLayer.bounds).cgPath
  62.         borderLayer.strokeColor = UIColor.black.cgColor
  63.         borderLayer.fillColor = UIColor.clear.cgColor
  64.  
  65.         gradientLayer.mask = borderLayer
  66.     }
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top