Apply vertical alpha gradient to UITableView - swift

I'm new to iOS development and am trying to learn Swift. I'd like to apply a vertical alpha gradient to a UITableView, but am having some trouble.
Originally following this SO post, I did the following:
var gradientMaskLayer:CAGradientLayer = CAGradientLayer()
gradientMaskLayer.frame = myTableView.bounds
gradientMaskLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
gradientMaskLayer.locations = [0.0, 0.05]
myTableView.layer.mask = gradientMaskLayer
After getting the error Array element cannot be bridged to Objective-C and reading this SO post I modified the two arrays used:
var gradientMaskLayer:CAGradientLayer = CAGradientLayer()
var gradientMaskColors:NSArray = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
var gradientMaskLocations:NSArray = [0.0, 0.05]
gradientMaskLayer.frame = myTableView.bounds
gradientMaskLayer.colors = gradientMaskColors
gradientMaskLayer.locations = gradientMaskLocations
myTableView.layer.mask = gradientMaskLayer
And now get the error Value failed to bridge from Swift type to a Objective-C type
I'm struggling to find a solution. Can any lend some assistance?

You should mask the superview, not the view itself.
Here's an example:
let gradient = CAGradientLayer()
gradient.frame = tableView.superview?.bounds ?? .null
gradient.colors = [UIColor.clear.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.clear.cgColor]
gradient.locations = [0.0, 0.15, 0.25, 0.75, 0.85, 1.0]
tableView.superview?.layer.mask = gradient
tableView.backgroundColor = .clear
Result:
You can change the orientation by changing the startPoint and endpoint properties. The default values (vertically) are (0.5, 0.0) and (0.5, 1) respectively. Point (0,0) is the bottom-left corner of the layer and (1,1) is the top-right corner. For example, if you want to apply that mask horizontally instead of vertically, just do:
gradient.startPoint = .init(x: 0.0, y: 0.5)
gradient.endPoint = .init(x: 1.0, y: 0.5)
One more thing: if you're using AutoLayout, then you need to update the layer with the correct CGRect value. I usually override layoutSubviews() method to update it like gradient.frame = tableView.superview?.bounds ?? .null.

So I believe I have a solution to your problem, but I'm not sure that I fully understand it. The problem seems to arise when you try to create an implicitly unwrapped AnyObject array, containing only implicitly unwrapped Core Foundation types, i.e.:
let implicitlyUnwrappedCGColor:CGColor! = UIColor.clearColor().CGColor
let implicitlyUnwrappedAnyObjectArray:[AnyObject]! = [implicitlyUnwrappedCGColor]
gives the array element cannot be bridged to Objective-C error.
It feels like this must be a Swift compiler issue, particularly as the following, where the implicitly unwrapped CGColor is declared as an implicitly unwrapped AnyObject, seems to make the compiler happy again:
let implicitlyUnwrappedCGColor:AnyObject! = UIColor.clearColor().CGColor
let implicitlyUnwrappedAnyObjectArray:[AnyObject]! = [implicitlyUnwrappedCGColor]
as does sticking a standard Objective-C object into the array:
let implicitlyUnwrappedCGColor:CGColor! = UIColor.clearColor().CGColor
let uiColor = UIColor.clearColor()
let implicitlyUnwrappedAnyObjectArray:[AnyObject]! = [implicitlyUnwrappedCGColor, uiColor]
In any case, try the following as a solution to your issue:
var gradientMaskLayer:CAGradientLayer = CAGradientLayer()
gradientMaskLayer.frame = myTableView.bounds
gradientMaskLayer.colors = [UIColor.clearColor().CGColor!, UIColor.blackColor().CGColor!]
gradientMaskLayer.locations = [0.0, 0.05]
myTableView.layer.mask = gradientMaskLayer

Related

Draw a line with a gradient using NSBezierPath, CAShapeLayer, and CAGradientLayer

I have a macOS app where I draw lines and other figures.
I use NSBezierPath to form the lines or figures and then add it to the CAShapeLayer's path and finally, add the CAShapeLayer to the view.
This all works fine and I have a single stroke color. However, I want the lines/figures not to be of a single color but of multiple colors(gradient). I know this can be done through CAGradientLayer and tried a few examples from other SO questions showing iOS variants but they didn't work for me.
Below is a code snippet from the app:
startPoint = point
currentPath = NSBezierPath()
currentShape = CAShapeLayer()
currentShape?.lineWidth = lineWeight
currentShape?.strokeColor = strokeColor.cgColor
currentShape?.fillColor = fillColor.cgColor
currentShape?.lineJoin = CAShapeLayerLineJoin.round
currentShape?.lineCap = CAShapeLayerLineCap.round
currentPath?.move(to: point)
currentPath?.line(to: point)
currentShape?.path = currentPath?.cgPath
view.layer?.addSublayer(currentShape!)
currentGradient = CAGradientLayer()
currentGradient?.mask = currentShape
currentGradient?.frame = currentShape!.frame
currentGradient?.colors = [NSColor.red.cgColor, NSColor.black.cgColor]
view.layer?.addSublayer(currentGradient!)
// some more code here that I omitted (to draw shapes with NSBezierPath)
if let shape = currentShape {
shape.path = currentPath?.cgPath
currentGradient?.mask = shape
currentGradient?.frame = shape.frame
}
If I remove the code that involves currentGradient then I see the lines/figures (in one solid color) but when I add the gradient part, I do not see anything. What am I doing wrong in the above code?
Any help or hints would be really appreciated.
If you have searched, then you know the answer. You cannot stroke a shape with a gradient. Instead, you mask to a gradient; the shape layer becomes the mask whereby the gradient layer is revealed. Example (v is a view in the window):
let grad = CAGradientLayer()
grad.frame = v.bounds
v.layer?.addSublayer(grad)
grad.colors = [NSColor.red.cgColor, NSColor.blue.cgColor]
let shape = CAShapeLayer()
shape.frame = v.bounds
shape.lineWidth = 3
shape.fillColor = NSColor.clear.cgColor
shape.strokeColor = NSColor.black.cgColor
let path = CGPath(ellipseIn: v.bounds.insetBy(dx: 4, dy: 4), transform: nil)
shape.path = path
grad.mask = shape

Center a view inside of an UITableViewCell? Looks centered in the UI hierarchy, but not in the actual app?

I'm trying to center a custom UIView in a UITableViewCell. Something fairly basic imo. I used this code to create the UIView, I found it here on stackoverflow:
class SkeletonView: UIView {
var startLocations : [NSNumber] = [-1.0,-0.5, 0.0]
var endLocations : [NSNumber] = [1.0,1.5, 2.0]
var gradientBackgroundColor : CGColor = UIColor(white: 0.85, alpha: 1.0).cgColor
var gradientMovingColor : CGColor = UIColor(white: 0.75, alpha: 1.0).cgColor
var movingAnimationDuration : CFTimeInterval = 0.8
var delayBetweenAnimationLoops : CFTimeInterval = 1.0
lazy var gradientLayer : CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.colors = [
gradientBackgroundColor,
gradientMovingColor,
gradientBackgroundColor
]
gradientLayer.locations = self.startLocations
self.layer.addSublayer(gradientLayer)
return gradientLayer
}()
func startAnimating(){
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = self.startLocations
animation.toValue = self.endLocations
animation.duration = self.movingAnimationDuration
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
let animationGroup = CAAnimationGroup()
animationGroup.duration = self.movingAnimationDuration + self.delayBetweenAnimationLoops
animationGroup.animations = [animation]
animationGroup.repeatCount = .infinity
self.gradientLayer.add(animationGroup, forKey: animation.keyPath)
}
func stopAnimating() {
self.gradientLayer.removeAllAnimations()
}
}
Then I just added a view to my cell xib, centered horizontally, leading edge +15, top +15 and bottom +15 (with priority 900 so that autolayout doesn't freak out about the height being 320 instead of its calculated value of 320.1). This way it is centered in the xib preview.
When running the app it looks like this, as you can see there is a gap on the left side, but not on the right side, so its not centered:
But then when I take a look at the UI hierarchy, it is centered?!
Remove centered horizontally contraint and add trailing constraint to 15 will resolve your issue
its good enough on my side
Nevermind, I found the problem. The UIView was placed correctly, however the gradientLayer I placed overtop was getting a wrong size. So I added the line
gradientLayer.frame = self.bounds
in the layoutSubviews function inside the skeleton UIView class.

CAShapeLayer disappears while moving

CAShapeLayer disappears while moving to another monitor, but not always
Tried searching for code examples
override func draw(_ dirtyRect: NSRect)
{
//super.draw(dirtyRect)
image?.lockFocus()
print("SelectionRect::draw")
if (shapeLayerIsVisible) {
auxLayer.removeFromSuperlayer()
shapeLayer.removeFromSuperlayer()
}
//let origin = frame.origin
auxLayer = CAShapeLayer()
auxLayer.strokeColor = NSColor.white.cgColor
auxLayer.fillColor = nil
auxLayer.lineWidth = 1.0
//rectSize = CGSize(width: x2 - x1, height: y2 - y1)
let selectionRect = frame //CGRect(x: origin.x, y: origin.y, width: frame.size.width, height: frame.size.height)
let auxPath = CGMutablePath()
//print("x1: \(x1), y1: \(y1), x2: \(x2), y2: \(y2), width: \(rectSize.width), height: \(rectSize.height)")
auxPath.addRect(selectionRect)
auxLayer.path = auxPath
layer?.addSublayer(auxLayer)
shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = NSColor.black.cgColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = 1.0
shapeLayer.lineDashPattern = [5, 5]
let path = CGMutablePath()
path.addRect(selectionRect)
shapeLayer.path = path
let lineDashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
lineDashAnimation.fromValue = 0
lineDashAnimation.toValue = shapeLayer.lineDashPattern?.reduce(0) { $0 + $1.intValue }
lineDashAnimation.duration = 1
lineDashAnimation.repeatCount = Float.greatestFiniteMagnitude
shapeLayer.add(lineDashAnimation, forKey: nil)
shapeLayerIsVisible = true
layer?.addSublayer(shapeLayer)
I've got an 5K iMac with two external 4K monitors (all three scaled to look like 2560x1440 if that matters). With the given code, the NSView is initialized with x: 0, y:0, width: 100, height: 100. All works well, I can drag the Windows around on all three monitors. When I moved the Layer with the mouse to a different position and than drag the window to a different monitor the Shape disappears.
Edit: I fixed it by calling draw(9 at the end of each mouseDragged()-Event and chaninging selectionRect from frame to bounds. It works, but is that a clean solution?
Don't call draw() yourself, per Apple's documentation:
You should never call draw() directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.

Drawing a gradient color in an arc with a rounded edge

I want to replicate this in Swift.. reading further: How to draw a linear gradient arc with Qt QPainter?
I've figured out how to draw a gradient inside of a rectangular view:
override func drawRect(rect: CGRect) {
let currentContext = UIGraphicsGetCurrentContext()
CGContextSaveGState(currentContext)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let startColor = MyDisplay.displayColor(myMetric.currentValue)
let startColorComponents = CGColorGetComponents(startColor.CGColor)
let endColor = MyDisplay.gradientEndDisplayColor(myMetric.currentValue)
let endColorComponents = CGColorGetComponents(endColor.CGColor)
var colorComponents
= [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]]
var locations: [CGFloat] = [0.0, 1.0]
let gradient = CGGradientCreateWithColorComponents(colorSpace, &colorComponents, &locations, 2)
let startPoint = CGPointMake(0, 0)
let endPoint = CGPointMake(1, 8)
CGContextDrawLinearGradient(currentContext, gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsAfterEndLocation)
CGContextRestoreGState(currentContext)
}
and how to draw an arc
func drawArc(color: UIColor, x: CGFloat, y: CGFloat, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, lineWidth: CGFloat, clockwise: Int32) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, lineWidth)
CGContextSetStrokeColorWithColor(context,
color.CGColor)
CGContextAddArc(context, x, y, radius, startAngle, endAngle, clockwise)
CGContextStrokePath(context)
}
With the gradient, that took up the entire view. I was unsure how to limit the gradient to a particular area so I made a subclass of UIView, modified the frame and used the gradient code (first snippet).
For arcs, I've used the second snippet. I'm thinking I can draw an arc and then draw a circle at the end of the arc to smooth out the arc with a rounded finish. How can I do this and draw a gradient over the arc shape?
Please ignore the purple mark. The first picture is the beginning of the gradient arc from my specification, the second is the end of the gradient arc, below and to the left of the beginning arc.
How can I draw this in Swift with Core Graphics?
Exact code for 2019 with true circular gradient and totally flexible end positions:
These days basically you simply have a gradient layer and mask for that layer.
So step one, you need a "mask".
What the heck is a "mask" in iOS?
In iOS, you actually use a CAShapeLayer to make a mask.
This is confusing. It should be called something like 'CAShapeToUseAsAMaskLayer'
But that's how you do it, a CAShapeLayer.
Step two. In layout, you must resize the shape layer. And that's it.
So basically it's just this:
class SweetArc: UIView {
open override func layoutSubviews() {
super.layoutSubviews()
arcLayer.frame = bounds
gradientLayer.frame = bounds
}
private lazy var gradientLayer: CAGradientLayer = {
let l = CAGradientLayer()
...
l.mask = arcLayer
layer.addSublayer(l)
return l
}()
private lazy var arcLayer: CAShapeLayer = {
let l = CAShapeLayer()
...
return l
}()
}
That's the whole thing.
Note that the mask of the gradient layer is indeed set as the shape layer, which we have named "arcLayer".
A shape layer is used as a mask.
Here's the exact code for the two layers:
private lazy var gradientLayer: CAGradientLayer = {
// recall that .conic is finally available in 12 !
let l = CAGradientLayer()
l.type = .conic
l.colors = [
UIColor.yellow,
UIColor.red
].map{$0.cgColor}
l.locations = [0, 1]
l.startPoint = CGPoint(x: 0.5, y: 0.5)
l.endPoint = CGPoint(x: 0.5, y: 0)
l.mask = arcLayer
layer.addSublayer(l)
return l
}()
private lazy var arcLayer: CAShapeLayer = {
let l = CAShapeLayer()
l.path = arcPath
// to use a shape layer as a mask, you mask with white-on-clear:
l.fillColor = UIColor.clear.cgColor
l.strokeColor = UIColor.white.cgColor
l.lineWidth = lineThick
l.lineCap = CAShapeLayerLineCap.round
l.strokeStart = 0.4 // try values 0-1
l.strokeEnd = 0.5 // try values 0-1
return l
}()
Again, notice arcLayer is a shape layer you are using as a mask - you do NOT actually add it as a subview.
Remember that shape layers used as masks do not! get added as subviews.
That can be a source of confusion. It's not a "layer" at all.
Finally, notice arcLayer uses a path arcPath.
Construct the path perfectly so that strokeStart and strokeEnd work correctly.
You want to build the path perfectly.
So that it is very easy to set the stroke start and stroke end values.
And they make sense by perfectly and correctly running clockwise, from the top, from 0 to 1.
Here's the exact code for that:
private let lineThick: CGFloat = 10.0
private let outerGap: CGFloat = 10.0
private let beginFraction: CGFloat = 0 // 0 means from top; runs clockwise
private lazy var arcPath: CGPath = {
let b = beginFraction * .pi * 2.0
return UIBezierPath(
arcCenter: bounds.centerOfCGRect(),
radius: bounds.width / 2.0 - lineThick / 2.0 - outerGap,
startAngle: .pi * -0.5 + b,
endAngle: .pi * 1.5 + b,
clockwise: true
).cgPath
}()
You're done!
override func draw(_ rect: CGRect) {
//Add gradient layer
let gl = CAGradientLayer()
gl.frame = rect
gl.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
layer.addSublayer(gl)
//create mask in the shape of arc
let sl = CAShapeLayer()
sl.frame = rect
sl.lineWidth = 15.0
sl.strokeColor = UIColor.red.cgColor
let path = UIBezierPath()
path.addArc(withCenter: .zero, radius: 250.0, startAngle: 10.0.radians, endAngle: 60.0.radians, clockwise: true)
sl.fillColor = UIColor.clear.cgColor
sl.lineCap = kCALineCapRound
sl.path = path.cgPath
//Add mask to gradient layer
gl.mask = sl
}
Hope this helps!!

Swift: Rounded View with inner shadow

I am trying to implement the solution here (which I converted to Swift): How to create rounded UITextField with inner shadow
My code is as follows:
mobileInputView.layer.cornerRadius = 5.0;
let shadowLayer = CAShapeLayer()
shadowLayer.frame = mobileInputView.bounds;
// Standard shadow stuff
shadowLayer.shadowColor = UIColor(white: 0, alpha: 1).CGColor
shadowLayer.shadowOffset = CGSizeMake(0.0, 0.0)
shadowLayer.shadowOpacity = 1.0
shadowLayer.shadowRadius = 4
// Causes the inner region in this example to NOT be filled.
shadowLayer.fillRule = kCAFillRuleEvenOdd
// Create the larger rectangle path.
let path = CGPathCreateMutable();
CGPathAddRect(path, nil, CGRectInset(mobileInputView.bounds, -42, -42));
// Add the inner path so it's subtracted from the outer path.
// someInnerPath could be a simple bounds rect, or maybe
// a rounded one for some extra fanciness.
let someInnerPath = UIBezierPath(roundedRect: mobileInputView.bounds, cornerRadius:5.0).CGPath
CGPathAddPath(path, nil, someInnerPath)
CGPathCloseSubpath(path);
shadowLayer.path = path
//CGPathRelease(path);
mobileInputView.layer.addSublayer(shadowLayer)
//[[_textField layer] addSublayer:shadowLayer];
let maskLayer = CAShapeLayer()
maskLayer.path = someInnerPath
shadowLayer.mask = maskLayer
But the view ends up coming out like this:
The width of the component is correct, I can type until the edge of the screen, it's just the border that comes out a bad size. If I set the background colour of the view I can see the view itself is being sized correctly.
If I try using .frame instead of .bounds I get the same result.
A much simpler way to achieve this is to modify the UITextField directly without have the outlining UIView and the label:
let label = UILabel(frame: CGRectMake(1, 1, 125, 25))
label.text = "Mobile number:"
label.textAlignment = NSTextAlignment.Right
mobileNumber.leftView = label
mobileNumber.leftViewMode = UITextFieldViewMode.Always
mobileNumber.borderStyle = UITextBorderStyle.Bezel;
mobileNumber.layer.borderWidth = 1.0
mobileNumber.layer.borderColor = UIColor.grayColor().CGColor
mobileNumber.layer.cornerRadius = 5.0