Last active
May 12, 2018 22:59
-
-
Save knightbenax/f211e95123b35bf31dd9fd63f9a543d4 to your computer and use it in GitHub Desktop.
GradientView in Swift/iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class CustomDarkUIView: UIView { | |
let gradientLayer = CAGradientLayer() | |
override func layoutSubviews() { | |
// resize your layers based on the view's new frame | |
super.layoutSubviews() | |
gradientLayer.frame = self.bounds | |
let color1 = hexStringToUIColor(hex: "498207").cgColor | |
let color2 = hexStringToUIColor(hex: "4C6100").cgColor | |
gradientLayer.colors = [color1, color2] | |
gradientLayer.locations = [0.0, 0.8] | |
gradientLayer.startPoint = CGPoint(x: 0, y: 0) | |
gradientLayer.endPoint = CGPoint(x: 1, y: 1) | |
self.layer.insertSublayer(gradientLayer, at: 0) | |
} | |
func hexStringToUIColor (hex:String) -> UIColor { | |
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() | |
if (cString.hasPrefix("#")) { | |
cString.remove(at: cString.startIndex) | |
} | |
if ((cString.count) != 6) { | |
return UIColor.gray | |
} | |
var rgbValue:UInt32 = 0 | |
Scanner(string: cString).scanHexInt32(&rgbValue) | |
return UIColor( | |
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
alpha: CGFloat(1) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment