How to put a gradient in a background button witch contains a system image? - swift

I have a button with a system image:
#IBOutlet weak var ampouleButton: UIButton!
in the viewdid load, i put this:
let ampouleButtonConfig = UIImage.SymbolConfiguration(
pointSize: 30,
weight: .regular,
scale: .large)
let ampouleButtonImage = UIImage(
systemName: "lightbulb",
withConfiguration: ampouleButtonConfig)
ampouleButton.backgroundColor = Theme.gold03 // i need to put here a gradient
ampouleButton.setImage(ampouleButtonImage, for: .normal)
ampouleButton.tintColor = Theme.blanc
ampouleButton.layer.cornerRadius = ampouleButton.frame.height / 2
ampouleButton.layer.shadowOpacity = 0.4
ampouleButton.layer.shadowRadius = 3
ampouleButton.layer.shadowOffset =
CGSize(width: 0, height: 5)
ampouleButton.alpha = 1
instead of the background color, i need to put a gradient.
i tested this but it didn't work:
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.ampouleButton.bounds
gradientLayer.colors = [UIColor.yellow.cgColor, UIColor.white.cgColor]
ampouleButton.layer.insertSublayer(gradientLayer, at: 0)

Actually, the button image goes behind the layer. Try this:
extension UIButton {
func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = .init(x: 0.5, y: 0), endGradient: CGPoint = .init(x: 0.5, y: 1)) {
// check first if there is already a gradient layer to avoid adding more than one
let gradientLayer = CAGradientLayer()
gradientLayer.cornerRadius = radius
gradientLayer.colors = colors
gradientLayer.startPoint = startGradient
gradientLayer.endPoint = endGradient
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
}
}
And in the viewDidLoad put:
ampouleButton.applyGradient(colors: [Theme.bleu!.cgColor, Theme.softBlue!.cgColor], radius: self.ampouleButton.frame.height / 2, startGradient: CGPoint(x: 0, y: 0.5), endGradient: CGPoint(x: 1, y: 0))
if let imgView = ampouleButton.imageView { ampouleButton.bringSubviewToFront(imgView) }
Find applyGradient function from here : https://stackoverflow.com/a/62093932/2303865

Related

how do i set the background color of UIViews to be a gradient color in swift?

Im trying to set the color of my button and labels to a gradient color in swift with the following code:
extension UIView {
func setGradientColor(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0,0.1]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}
and then in the sign in form i use the extension like this:
let logo: UILabel = {
let logo = UILabel()
logo.text = "Logo"
logo.setGradientColor(colorOne: UIColor.blue, colorTwo: UIColor.yellow)
logo.textAlignment = .center
logo.font = UIFont.boldSystemFont(ofSize: 59)
return logo
}()
but it still shows up as black.
how do i fix this?
What you posted i review that ... call setGradietColor(colorOne: UIColor.blue, colorTwo: UIColor.yellow) after setting the frame or constraints to the logo view
You can add gradient layer in your view
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.black.cgColor, UIColor.blue.cgColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x : 0.0, y : 0)
gradient.endPoint = CGPoint(x :0.0, y: 0.5) // you need to play with 0.15 to adjust gradient vertically
gradient.frame = view.bounds
view.layer.addSublayer(gradient)
You're facing this issue because you're not updating the frame of gradientLayer when bounds of logo updates. For example in ViewController you can give this code if you can have the reference to your gradientLayer.
class ViewController: UIViewController {
var gradient: CAGradientLayer?
let logo: UILabel = {
let logo = UILabel()
logo.text = "Logo"
gradient = logo.setGradietColor(colorOne: UIColor.blue, colorTwo: UIColor.yellow)
logo.textAlignment = .center
logo.font = UIFont.boldSystemFont(ofSize: 59)
return logo
}()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradient?.frame = logo.bounds
}
}
Try returning the layer from your method and modify your function like this:
extension UIView {
#discardableResult
func setGradietColor(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0,0.1]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
return layer
}
}

Swift make UIView border into Gradient Color

I want to create a gradient border on a UIView.
The following code can produce a solid for the view Box1.
nothing I have found allows me to change the frameColor to a gradient.
var frameColor = UIColor.red.cgColor
var leftBorder = CALayer()
leftBorder.frame = CGRect(x: 0.0, y: 0, width: 1, height: box1.frame.size.height )
leftBorder.backgroundColor = frameColor
I am using Swift 5 and Xcode 11.
Thank you.
Try with below extension
public extension UIView {
private static let kLayerNameGradientBorder = "GradientBorderLayer"
func setGradientBorder(
width: CGFloat,
colors: [UIColor],
startPoint: CGPoint = CGPoint(x: 0.5, y: 0),
endPoint: CGPoint = CGPoint(x: 0.5, y: 1)
) {
let existedBorder = gradientBorderLayer()
let border = existedBorder ?? CAGradientLayer()
border.frame = bounds
border.colors = colors.map { return $0.cgColor }
border.startPoint = startPoint
border.endPoint = endPoint
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0).cgPath
mask.fillColor = UIColor.clear.cgColor
mask.strokeColor = UIColor.white.cgColor
mask.lineWidth = width
border.mask = mask
let exists = existedBorder != nil
if !exists {
layer.addSublayer(border)
}
}
func removeGradientBorder() {
self.gradientBorderLayer()?.removeFromSuperlayer()
}
private func gradientBorderLayer() -> CAGradientLayer? {
let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
if borderLayers?.count ?? 0 > 1 {
fatalError()
}
return borderLayers?.first as? CAGradientLayer
}
}
Usage
self.borderView.setGradientBorder(width: 5.0, colors: [UIColor.red , UIColor.blue])
I hope this will reach your requirement.
https://medium.com/#kushal0409/gradient-button-3dc8ef763039
There is no off-the-shelf way to do this, but you could build it yourself.
Off the top of my head, the approach might look like this:
Create a CAGradientLayer and set it up to draw your gradient as
desired.
Create a CAShapeLayer that contains an empty rectangle that is your
frame.
Add your shape layer as the mask of your gradient layer.
Add the gradient layer to your view as a sub-layer of the view's
content layer.
Swift 5 extension (works with corner radius)
extension UIView {
func gradientBorder(colors: [UIColor], isVertical: Bool){
self.layer.masksToBounds = true
//Create gradient layer
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
gradient.colors = colors.map({ (color) -> CGColor in
color.cgColor
})
//Set gradient direction
if(isVertical){
gradient.startPoint = CGPoint(x: 0.5, y: 0)
gradient.endPoint = CGPoint(x: 0.5, y: 1)
}
else {
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 0.5)
}
//Create shape layer
let shape = CAShapeLayer()
shape.lineWidth = 1
shape.path = UIBezierPath(roundedRect: gradient.frame.insetBy(dx: 1, dy: 1), cornerRadius: self.layer.cornerRadius).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
//Add layer to view
self.layer.addSublayer(gradient)
gradient.zPosition = 0
}
}

How to add rounded corners to a UIView with gradient applied?

I've written custom subclass of UIView that draws a gradient inside of it:
import UIKit
#IBDesignable
class PlayerCellView: UIView {
var startColor: UIColor = UIColor(red:0.20, green:0.75, blue:1.00, alpha:1.00)
var endColor: UIColor = UIColor(red:0.07, green:0.42, blue:1.00, alpha:1.00)
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor]
let locations : [CGFloat] = [0.0, 1.0]
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: locations)
context?.drawLinearGradient(gradient!, start: CGPoint.zero, end: CGPoint(x: 0, y: self.bounds.height), options: .drawsAfterEndLocation)
}
}
How would I now apply rounded edges to this view?
use this extension method:
extension UIView {
func addGradientLayer(with colors: [CGColor], startPoint: CGPoint, endPoint: CGPoint, locations: [NSNumber] = [0.0, 1.0], frame: CGRect = CGRect.zero) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
gradientLayer.locations = locations
gradientLayer.frame = frame
gradientLayer.cornerRadius = self.layer.cornerRadius
self.layer.insertSublayer(gradientLayer, at: 0)
}
}
You can add a rounded corner UIView with gradient using the following method:
func makeCircularGradient(){
let circularView = UIView()
self.view.addSubview(circularView)
circularView.translatesAutoresizingMaskIntoConstraints = false
circularView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
circularView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
circularView.widthAnchor.constraint(equalToConstant: 200).isActive = true
circularView.heightAnchor.constraint(equalToConstant: 200).isActive = true
self.view.layoutIfNeeded()
let gradient = CAGradientLayer()
gradient.frame = circularView.bounds
gradient.colors = [UIColor.blue.cgColor,
UIColor.red.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 1, y: 0)
circularView.layer.addSublayer(gradient)
let circularPath = CGMutablePath()
circularPath.addArc(center: CGPoint.init(x: circularView.bounds.width / 2, y: circularView.bounds.height / 2), radius: circularView.bounds.width / 2, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true, transform: .identity)
let maskLayer = CAShapeLayer()
maskLayer.path = circularPath
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.fillColor = UIColor.red.cgColor
circularView.layer.mask = maskLayer
}
Make a UIView and set the constraints as you see fit
Make a CAGradientLayer with colours of your choice
Make a circular mask layer and apply to the UIView.
The result will be something like below:
Making a curved corner radius View with gradient is a little bit more difficult than the circular one. And can be done like :
func makeCurvedCornerGradient(){
let circularView = UIView()
self.view.addSubview(circularView)
circularView.translatesAutoresizingMaskIntoConstraints = false
circularView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
circularView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
circularView.widthAnchor.constraint(equalToConstant: 200).isActive = true
circularView.heightAnchor.constraint(equalToConstant: 200).isActive = true
self.view.layoutIfNeeded()
let gradient = CAGradientLayer()
gradient.frame = circularView.bounds
gradient.colors = [UIColor.blue.cgColor,
UIColor.red.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 1, y: 0)
circularView.layer.addSublayer(gradient)
let circularPath = CGMutablePath()
circularPath.move(to: CGPoint.init(x: 20, y: 0))
circularPath.addLine(to: CGPoint.init(x: circularView.bounds.width - 20, y: 0))
circularPath.addQuadCurve(to: CGPoint.init(x: circularView.bounds.width, y: 20), control: CGPoint.init(x: circularView.bounds.width, y: 0))
circularPath.addLine(to: CGPoint.init(x: circularView.bounds.width, y: circularView.bounds.height - 20))
circularPath.addQuadCurve(to: CGPoint.init(x: circularView.bounds.width - 20, y: circularView.bounds.height), control: CGPoint.init(x: circularView.bounds.width, y: circularView.bounds.height))
circularPath.addLine(to: CGPoint.init(x: 20, y: circularView.bounds.height))
circularPath.addQuadCurve(to: CGPoint.init(x: 0, y: circularView.bounds.height - 20), control: CGPoint.init(x: 0, y: circularView.bounds.height))
circularPath.addLine(to: CGPoint.init(x: 0, y: 20))
circularPath.addQuadCurve(to: CGPoint.init(x: 20, y: 0), control: CGPoint.init(x: 0, y: 0))
let maskLayer = CAShapeLayer()
maskLayer.path = circularPath
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.fillColor = UIColor.red.cgColor
circularView.layer.mask = maskLayer
}
Change the values according to your need.
Output:
You can possibly use the Following Code:
func setGradientBorderWidthColor(view: UIView)
{
let gradientColor = CAGradientLayer()
gradientColor.frame = CGRect(origin: CGPoint.zero, size: view.frame.size)
gradientColor.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
let pathWithRadius = UIBezierPath(roundedRect:view.bounds, byRoundingCorners:[.topRight, .topLeft, .bottomLeft , .bottomRight], cornerRadii: CGSize(width: 20.0, height: 20.0))
let shape = CAShapeLayer()
shape.lineWidth = 3
shape.path = pathWithRadius.cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradientColor.mask = shape
view.layer.mask = shape
view.layer.addSublayer(gradientColor)
}
You can use this as:
let myView = UIView()
myView.backgroundColor = UIColor.gray
myView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
setGradientBorderWidthColor(view: myView)
self.view.addSubview(myView)
Output is like this:
Hope this Helps!

round image in swift

I'm trying to make an image round. I always used maskCircle but this time it does not work. I wrote the code in UICollectionViewCell's awakeFromNib and I can not use viewDidLayoutSubviews since I'm dequeueing the cell in cellForItemAt function. So this is the code:
#IBOutlet weak var storeLogo: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
storeLogo.maskCircle()
storeLogo.clipsToBounds = true
}
and the imageView looks like this:
imageView
edit:
it seemed to work fine, but i have the problem again.
this is the code in awakeFromNib now:
super.awakeFromNib()
storeLogo.clipsToBounds = true
storeLogo.layer.cornerRadius = storeLogo.frame.width / 2
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 55, height: 55))
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.colors = [Color.storeName?.cgColor, Color.idTint?.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 2
let radius: CGFloat = 27
shape.path = UIBezierPath(roundedRect: CGRect(x: -2.5, y: -14, width: 2.0 * radius, height: 2.0 * radius), cornerRadius: radius).cgPath
shape.position = CGPoint(x: self.frame.midX - radius, y: self.frame.midY - radius)
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
self.storeLogo.layer.addSublayer(gradient)
and the image is not round as you can see in this image: imageView
i
i don't know why the image is not a circle now. any idea?!
If you want to do round clip on UIImageView set cornerRadius of UIImageView.
storeLogo.layer.cornerRadius = storeLogo.frame.width / 2
storeLogo.clipsToBounds = true

Why doesn't UIView.animateWithDuration affect this custom view?

I designed a custom header view that masks an image and draws a border on the bottom edge, which is an arc. It looks like this:
Here's the code for the class:
class HeaderView: UIView
{
private let imageView = UIImageView()
private let dimmerView = UIView()
private let arcShape = CAShapeLayer()
private let maskShape = CAShapeLayer() // Masks the image and the dimmer
private let titleLabel = UILabel()
#IBInspectable var image: UIImage? { didSet { self.imageView.image = self.image } }
#IBInspectable var title: String? { didSet {self.titleLabel.text = self.title} }
#IBInspectable var arcHeight: CGFloat? { didSet {self.setupLayers()} }
// MARK: Initialization
override init(frame: CGRect)
{
super.init(frame:frame)
initMyStuff()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
initMyStuff()
}
override func prepareForInterfaceBuilder()
{
backgroundColor = UIColor.clear()
}
internal func initMyStuff()
{
backgroundColor = UIColor.clear()
titleLabel.font = Font.AvenirNext_Bold(24)
titleLabel.text = "TITLE"
titleLabel.textColor = UIColor.white()
titleLabel.layer.shadowColor = UIColor.black().cgColor
titleLabel.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
titleLabel.layer.shadowRadius = 0.0;
titleLabel.layer.shadowOpacity = 1.0;
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true
imageView.contentMode = UIViewContentMode.scaleAspectFill
addSubview(imageView)
dimmerView.frame = self.bounds
dimmerView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
addSubview(dimmerView)
addSubview(titleLabel)
// Add the shapes
self.layer.addSublayer(arcShape)
self.layer.addSublayer(maskShape)
self.layer.masksToBounds = true // This seems to be unneeded...test more
// Set constraints
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView .autoPinEdgesToSuperviewEdges()
titleLabel.autoCenterInSuperview()
}
func setupLayers()
{
let aHeight = arcHeight ?? 10
// Create the arc shape
arcShape.path = AppocalypseUI.createHorizontalArcPath(CGPoint(x: 0, y: bounds.size.height), width: bounds.size.width, arcHeight: aHeight)
arcShape.strokeColor = UIColor.white().cgColor
arcShape.lineWidth = 1.0
arcShape.fillColor = UIColor.clear().cgColor
// Create the mask shape
let maskPath = AppocalypseUI.createHorizontalArcPath(CGPoint(x: 0, y: bounds.size.height), width: bounds.size.width, arcHeight: aHeight, closed: true)
maskPath.moveTo(nil, x: bounds.size.width, y: bounds.size.height)
maskPath.addLineTo(nil, x: bounds.size.width, y: 0)
maskPath.addLineTo(nil, x: 0, y: 0)
maskPath.addLineTo(nil, x: 0, y: bounds.size.height)
//let current = CGPathGetCurrentPoint(maskPath);
//print(current)
let mask_Dimmer = CAShapeLayer()
mask_Dimmer.path = maskPath.copy()
maskShape.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor
maskShape.path = maskPath
// Apply the masks
imageView.layer.mask = maskShape
dimmerView.layer.mask = mask_Dimmer
}
override func layoutSubviews()
{
super.layoutSubviews()
// Let's go old school here...
imageView.frame = self.bounds
dimmerView.frame = self.bounds
setupLayers()
}
}
Something like this will cause it to just snap to the new size without gradually changing its frame:
UIView.animate(withDuration: 1.0)
{
self.headerView.arcHeight = self.new_headerView_arcHeight
self.headerView.frame = self.new_headerView_frame
}
I figure it must have something to do with the fact that I'm using CALayers, but I don't really know enough about what's going on behind the scenes.
EDIT:
Here's the function I use to create the arc path:
class func createHorizontalArcPath(_ startPoint:CGPoint, width:CGFloat, arcHeight:CGFloat, closed:Bool = false) -> CGMutablePath
{
// http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths
let arcRect = CGRect(x: startPoint.x, y: startPoint.y-arcHeight, width: width, height: arcHeight)
let arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.size.width/2, y: arcRect.origin.y + arcRadius);
let angle = acos(arcRect.size.width / (2*arcRadius));
let startAngle = CGFloat(M_PI)+angle // (180 degrees + angle)
let endAngle = CGFloat(M_PI*2)-angle // (360 degrees - angle)
// let startAngle = radians(180) + angle;
// let endAngle = radians(360) - angle;
let path = CGMutablePath();
path.addArc(nil, x: arcCenter.x, y: arcCenter.y, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false);
if(closed == true)
{path.addLineTo(nil, x: startPoint.x, y: startPoint.y);}
return path;
}
BONUS:
Setting the arcHeight property to 0 results in no white line being drawn. Why?
The Path property can't be animated. You have to approach the problem differently. You can draw an arc 'instantly', any arc, so that tells us that we need to handle the animation manually. If you expect the entire draw process to take say 3 seconds, then you might want to split the process to 1000 parts, and call the arc drawing function 1000 times every 0.3 miliseconds to draw the arc again from the beginning to the current point.
self.headerView.arcHeight is not a animatable property. It is only UIView own properties are animatable
you can do something like this
let displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode
let expectedFramesPerSecond = 60
var diff : CGFloat = 0
func update() {
let diffUpdated = self.headerView.arcHeight - self.new_headerView_arcHeight
let done = (fabs(diffUpdated) < 0.1)
if(!done){
self.headerView.arcHeight -= diffUpdated/(expectedFramesPerSecond*0.5)
self.setNeedsDisplay()
}
}