Add a border outside of a UIView (instead of inside) - ios

If a add a border of a view using code in a view like
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = 2.0f;
the border is added inside the view like the following:
the right view is the original view, as you can see, the black area of bordered view is less than the original one. but what I want to get is a border outside of original view, like this:. the black area is equal to original one, how can I implement it?

Unfortunately, there isn't simply a little property you can set to align the border to the outside. It draws aligned to the inside because the UIViews default drawing operations draw within its bounds.
The simplest solution that comes to mind would be to expand the UIView by the size of the border width when applying the border:
CGFloat borderWidth = 2.0f;
self.frame = CGRectInset(self.frame, -borderWidth, -borderWidth);
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = borderWidth;

With the above accepted best answer i made experiences with such not nice results and unsightly edges:
So i will share my UIView Swift extension with you, that uses a UIBezierPath instead as border outline – without unsightly edges (inspired by #Fattie):
// UIView+BezierPathBorder.swift
import UIKit
extension UIView {
fileprivate var bezierPathIdentifier:String { return "bezierPathBorderLayer" }
fileprivate var bezierPathBorder:CAShapeLayer? {
return (self.layer.sublayers?.filter({ (layer) -> Bool in
return layer.name == self.bezierPathIdentifier && (layer as? CAShapeLayer) != nil
}) as? [CAShapeLayer])?.first
}
func bezierPathBorder(_ color:UIColor = .white, width:CGFloat = 1) {
var border = self.bezierPathBorder
let path = UIBezierPath(roundedRect: self.bounds, cornerRadius:self.layer.cornerRadius)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
if (border == nil) {
border = CAShapeLayer()
border!.name = self.bezierPathIdentifier
self.layer.addSublayer(border!)
}
border!.frame = self.bounds
let pathUsingCorrectInsetIfAny =
UIBezierPath(roundedRect: border!.bounds, cornerRadius:self.layer.cornerRadius)
border!.path = pathUsingCorrectInsetIfAny.cgPath
border!.fillColor = UIColor.clear.cgColor
border!.strokeColor = color.cgColor
border!.lineWidth = width * 2
}
func removeBezierPathBorder() {
self.layer.mask = nil
self.bezierPathBorder?.removeFromSuperlayer()
}
}
Example:
let view = UIView(frame: CGRect(x: 20, y: 20, width: 100, height: 100))
view.layer.cornerRadius = view.frame.width / 2
view.backgroundColor = .red
//add white 2 pixel border outline
view.bezierPathBorder(.white, width: 2)
//remove border outline (optional)
view.removeBezierPathBorder()

For a Swift implementation, you can add this as a UIView extension.
extension UIView {
struct Constants {
static let ExternalBorderName = "externalBorder"
}
func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.whiteColor()) -> CALayer {
let externalBorder = CALayer()
externalBorder.frame = CGRectMake(-borderWidth, -borderWidth, frame.size.width + 2 * borderWidth, frame.size.height + 2 * borderWidth)
externalBorder.borderColor = borderColor.CGColor
externalBorder.borderWidth = borderWidth
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, atIndex: 0)
layer.masksToBounds = false
return externalBorder
}
func removeExternalBorders() {
layer.sublayers?.filter() { $0.name == Constants.ExternalBorderName }.forEach() {
$0.removeFromSuperlayer()
}
}
func removeExternalBorder(externalBorder: CALayer) {
guard externalBorder.name == Constants.ExternalBorderName else { return }
externalBorder.removeFromSuperlayer()
}
}

Ok, there already is an accepted answer but I think there is a better way to do it, you just have to had a new layer a bit larger than your view and do not mask it to the bounds of the view's layer (which actually is the default behaviour). Here is the sample code :
CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;
[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;
Of course this is if you want your border to be 1 unity large, if you want more you adapt the borderWidth and the frame of the layer accordingly.
This is better than using a second view a bit larger as a CALayer is lighter than a UIView and you don't have do modify the frame of myView, which is good for instance if myView is aUIImageView
N.B : For me the result was not perfect on simulator (the layer was not exactly at the right position so the layer was thicker on one side sometimes) but was exactly what is asked for on real device.
EDIT
Actually the problem I talk about in the N.B was just because I had reduced the screen of the simulator, on normal size there is absolutely no issue
Hope it helps

Well there is no direct method to do it
You can consider some workarounds.
Change and increase the frame and add bordercolor as you did
Add a view behind the current view with the larger size so that it appears as border.Can be worked as a custom class of view
If you dont need a definite border (clearcut border) then you can depend on shadow for the purpose
[view1 setBackgroundColor:[UIColor blackColor]];
UIColor *color = [UIColor yellowColor];
view1.layer.shadowColor = [color CGColor];
view1.layer.shadowRadius = 10.0f;
view1.layer.shadowOpacity = 1;
view1.layer.shadowOffset = CGSizeZero;
view1.layer.masksToBounds = NO;

Swift 5
extension UIView {
fileprivate struct Constants {
static let externalBorderName = "externalBorder"
}
func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) -> CALayer {
let externalBorder = CALayer()
externalBorder.frame = CGRect(x: -borderWidth, y: -borderWidth, width: frame.size.width + 2 * borderWidth, height: frame.size.height + 2 * borderWidth)
externalBorder.borderColor = borderColor.cgColor
externalBorder.borderWidth = borderWidth
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, at: 0)
layer.masksToBounds = false
return externalBorder
}
func removeExternalBorders() {
layer.sublayers?.filter() { $0.name == Constants.externalBorderName }.forEach() {
$0.removeFromSuperlayer()
}
}
func removeExternalBorder(externalBorder: CALayer) {
guard externalBorder.name == Constants.externalBorderName else { return }
externalBorder.removeFromSuperlayer()
}
}

Increase the width and height of view's frame with border width before adding the border:
float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = 2.0f;

I liked solution of #picciano
If you want exploding circle instead of square replace addExternalBorder function with:
func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) {
let externalBorder = CALayer()
externalBorder.frame = CGRect(x: -borderWidth, y: -borderWidth, width: frame.size.width + 2 * borderWidth, height: frame.size.height + 2 * borderWidth)
externalBorder.borderColor = borderColor.cgColor
externalBorder.borderWidth = borderWidth
externalBorder.cornerRadius = (frame.size.width + 2 * borderWidth) / 2
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, at: 0)
layer.masksToBounds = false
}

There is actually a very simple solution. Just set them both like this:
view.layer.borderWidth = 5
view.layer.borderColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.25).cgColor

How I placed a border around my UI view (main - SubscriptionAd) in Storyboard is to place it inside another UI view (background - BackgroundAd). The Background UIView has a background colour that matches the border colour i want, and the Main UIView has constraints value 2 from each side.
I will link the background view to my ViewController and then turn the border on and off by changing the background colour.

I liked solution of #picciano & #Maksim Kniazev. We can also create annular border with following:
func addExternalAnnularBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) {
let externalBorder = CALayer()
externalBorder.frame = CGRect(x: -borderWidth*2, y: -borderWidth*2, width: frame.size.width + 4 * borderWidth, height: frame.size.height + 4 * borderWidth)
externalBorder.borderColor = borderColor.cgColor
externalBorder.borderWidth = borderWidth
externalBorder.cornerRadius = (frame.size.width + 4 * borderWidth) / 2
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, at: 0)
layer.masksToBounds = false
}

Related

Tableview Xib Shadow Swift

Here is what I am trying to do:
The screenshot is taken from Iphone:
This is my code:
cell.shadowLayerView.layer.masksToBounds = false
cell.shadowLayerView.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.shadowLayerView.layer.shadowColor = UIColor.black.cgColor
cell.shadowLayerView.layer.shadowOpacity = 0.23
cell.shadowLayerView.layer.shadowRadius = 4
cell.shadowLayerView.layer.shadowPath = UIBezierPath(roundedRect: cell.shadowLayerView.bounds, cornerRadius: 2).cgPath
cell.shadowLayerView.layer.shouldRasterize = true
cell.shadowLayerView.layer.rasterizationScale = UIScreen.main.scale
cell.discriptionLbl.frame.size.width = UIScreen.main.bounds.size.width
This is my tableview xib. In original image show light gray color shadow all side(Top,Bottom,left,Right) but in taken image show all side shadow but why show extra shadow in right side and bottom side.
See Below Image:
Question: How to show same shadow from all side of the view like original image(shadow in light gray color)?
Can someone please explain to me how to solve this , i've tried to solve this issue but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
See the below code:
mainViewCorner.layer.shadowColor = UIColor.red.cgColor;
mainViewCorner.layer.shadowOffset = CGSize.zero //direction of shadow
mainViewCorner.layer.shadowOpacity = 1.0; // opacity for shadow
mainViewCorner.layer.shadowRadius = 0.0; //amount of shadow to blur
mainViewCorner.layer.cornerRadius = 4.0;
issue with your code was shadowOffset. It defines the direction of your shadow. If you want shadow on all sides - it must have zero value for both width and height.
try it
myView.layer.cornerRadius = 10
let shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 10)
myView.layer.masksToBounds = false
myView.layer.shadowColor = UIColor.gray.cgColor
myView.layer.shadowOffset = CGSize(width: 0, height: 2)
myView.layer.shadowOpacity = 0.5
Or you can use Sketch Shadow
extension CALayer {
func applySketchShadow(
color: UIColor = .black,
alpha: Float = 0.5,
x: CGFloat = 0,
y: CGFloat = 2,
blur: CGFloat = 4,
spread: CGFloat = 0)
{
shadowColor = color.cgColor
shadowOpacity = alpha
shadowOffset = CGSize(width: x, height: y)
shadowRadius = blur / 2.0
if spread == 0 {
shadowPath = nil
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(rect: rect).cgPath
}
}
}
apply Sketch Shadow
myView.layer.cornerRadius = 10
let shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 10)
myView.layer.applySketchShadow(
color: .black,
alpha: 0.5,
x: CGFloat(0),
y: CGFloat(10),
blur: 20,
spread: 0)
myView.layer.shadowPath = shadowPath.cgPath

Swift create extension for textfield shadow code

I have multiple textfield but all the textfield have same shadow effects, I need to use extension for that shadow code and use it shortly in viewdid load.
below code I am using
//MARK - Email TextField
email_textfield.borderStyle = .none
email_textfield.backgroundColor = UIColor.groupTableViewBackground // Use anycolor that give you a 2d look.
//To apply corner radius
email_textfield.layer.cornerRadius = email_textfield.frame.size.height / 2
//To apply border
email_textfield.layer.borderWidth = 0.25
email_textfield.layer.borderColor = UIColor.white.cgColor
//To apply Shadow
email_textfield.layer.shadowOpacity = 1
email_textfield.layer.shadowRadius = 1.0
email_textfield.layer.shadowOffset = CGSize.zero // Use any CGSize
email_textfield.layer.shadowColor = UIColor.lightGray.cgColor
//To apply padding
let paddingView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: email_textfield.frame.height))
email_textfield.leftView = paddingView
email_textfield.leftViewMode = UITextFieldViewMode.always
you can create extension like this
extension UITextField {
func applyCustomEffect() {
self.borderStyle = .none
self.backgroundColor = UIColor.groupTableViewBackground // Use anycolor that give you a 2d look.
//To apply corner radius
self.layer.cornerRadius = self.frame.size.height / 2
//To apply border
self.layer.borderWidth = 0.25
self.layer.borderColor = UIColor.white.cgColor
//To apply Shadow
self.layer.shadowOpacity = 1
self.layer.shadowRadius = 1.0
self.layer.shadowOffset = CGSize.zero // Use any CGSize
self.layer.shadowColor =
UIColor.lightGray.cgColor
self.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0)
}
}
And apply this effect like below
email_textfield.applyCustomEffect()

How to draw a circle path with color gradient stroke

I want to draw a circle with color gradient stroke like the following picture, on both iOS and macOS:
Is it possible to implement with CAShapeLayer or NSBezierPath/CGPath? Or any other ways?
In macOS 10.14 and later (as well as in iOS 12 and later), you can create a CAGradientLayer with a type of .conic, and then mask it with a circular arc. For example, for macOS:
class GradientArcView: NSView {
var startColor: NSColor = .white { didSet { setNeedsDisplay(bounds) } }
var endColor: NSColor = .blue { didSet { setNeedsDisplay(bounds) } }
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay(bounds) } }
private let gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.type = .conic
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
return gradientLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func layout() {
super.layout()
updateGradient()
}
}
private extension GradientArcView {
func configure() {
wantsLayer = true
layer?.addSublayer(gradientLayer)
}
func updateGradient() {
gradientLayer.frame = bounds
gradientLayer.colors = [startColor, endColor].map { $0.cgColor }
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
let path = CGPath(ellipseIn: bounds.insetBy(dx: bounds.width / 2 - radius, dy: bounds.height / 2 - radius), transform: nil)
let mask = CAShapeLayer()
mask.fillColor = NSColor.clear.cgColor
mask.strokeColor = NSColor.white.cgColor
mask.lineWidth = lineWidth
mask.path = path
gradientLayer.mask = mask
}
}
Or, in iOS:
#IBDesignable
class GradientArcView: UIView {
#IBInspectable var startColor: UIColor = .white { didSet { setNeedsLayout() } }
#IBInspectable var endColor: UIColor = .blue { didSet { setNeedsLayout() } }
#IBInspectable var lineWidth: CGFloat = 3 { didSet { setNeedsLayout() } }
private let gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.type = .conic
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
return gradientLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
updateGradient()
}
}
private extension GradientArcView {
func configure() {
layer.addSublayer(gradientLayer)
}
func updateGradient() {
gradientLayer.frame = bounds
gradientLayer.colors = [startColor, endColor].map { $0.cgColor }
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
let mask = CAShapeLayer()
mask.fillColor = UIColor.clear.cgColor
mask.strokeColor = UIColor.white.cgColor
mask.lineWidth = lineWidth
mask.path = path.cgPath
gradientLayer.mask = mask
}
}
In earlier OS versions you have to do something manual, such as stroking a series of arcs in different colors. For example, in macOS:
import Cocoa
/// This draws an arc, of length `maxAngle`, ending at `endAngle. This is `#IBDesignable`, so if you
/// put this in a separate framework target, you can use this class in Interface Builder. The only
/// property that is not `#IBInspectable` is the `lineCapStyle` (as IB doesn't know how to show that).
///
/// If you want to make this animated, just use a `CADisplayLink` update the `endAngle` property (and
/// this will automatically re-render itself whenever you change that property).
#IBDesignable
class GradientArcView: NSView {
/// Width of the stroke.
#IBInspectable var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay(bounds) } }
/// Color of the stroke (at full alpha, at the end).
#IBInspectable var strokeColor: NSColor = .blue { didSet { setNeedsDisplay(bounds) } }
/// Where the arc should end, measured in degrees, where 0 = "3 o'clock".
#IBInspectable var endAngle: CGFloat = 0 { didSet { setNeedsDisplay(bounds) } }
/// What is the full angle of the arc, measured in degrees, e.g. 180 = half way around, 360 = all the way around, etc.
#IBInspectable var maxAngle: CGFloat = 360 { didSet { setNeedsDisplay(bounds) } }
/// What is the shape at the end of the arc.
var lineCapStyle: NSBezierPath.LineCapStyle = .square { didSet { setNeedsDisplay(bounds) } }
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let gradations = 255
let startAngle = -endAngle + maxAngle
let center = NSPoint(x: bounds.midX, y: bounds.midY)
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
var angle = startAngle
for i in 1 ... gradations {
let percent = CGFloat(i) / CGFloat(gradations)
let endAngle = startAngle - percent * maxAngle
let path = NSBezierPath()
path.lineWidth = lineWidth
path.lineCapStyle = lineCapStyle
path.appendArc(withCenter: center, radius: radius, startAngle: angle, endAngle: endAngle, clockwise: true)
strokeColor.withAlphaComponent(percent).setStroke()
path.stroke()
angle = endAngle
}
}
}
Here is some code that worked for me. There's animations in it, but you can use the same principle to make a strokeEnd with a gradient.
A. Created a custom view 'Donut' and put this in the header:
#interface Donut : UIView
#property UIColor * fromColour;
#property UIColor * toColour;
#property UIColor * baseColour;
#property float lineWidth;
#property float duration;
-(void)layout;
-(void)animateTo:(float)percentage;
B. Then did the basic view setup and wrote these two methods:
-(void)layout{
//vars
float dimension = self.frame.size.width;
//1. layout views
//1.1 layout base track
UIBezierPath * donut = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(lineWidth/2, lineWidth/2, dimension-lineWidth, dimension-lineWidth)];
CAShapeLayer * baseTrack = [CAShapeLayer layer];
baseTrack.path = donut.CGPath;
baseTrack.lineWidth = lineWidth;
baseTrack.fillColor = [UIColor clearColor].CGColor;
baseTrack.strokeStart = 0.0f;
baseTrack.strokeEnd = 1.0f;
baseTrack.strokeColor = baseColour.CGColor;
baseTrack.lineCap = kCALineCapButt;
[self.layer addSublayer:baseTrack];
//1.2 clipView has mask applied to it
UIView * clipView = [UIView new];
clipView.frame = self.bounds;
[self addSubview:clipView];
//1.3 rotateView transforms with strokeEnd
rotateView = [UIView new];
rotateView.frame = self.bounds;
[clipView addSubview:rotateView];
//1.4 radialGradient holds an image of the colours
UIImageView * radialGradient = [UIImageView new];
radialGradient.frame = self.bounds;
[rotateView addSubview:radialGradient];
//2. create colours fromColour --> toColour and add to an array
//2.1 holds all colours between fromColour and toColour
NSMutableArray * spectrumColours = [NSMutableArray new];
//2.2 get RGB values for both colours
double fR, fG, fB; //fromRed, fromGreen etc
double tR, tG, tB; //toRed, toGreen etc
[fromColour getRed:&fR green:&fG blue:&fB alpha:nil];
[toColour getRed:&tR green:&tG blue:&tB alpha:nil];
//2.3 determine increment between fromRed and toRed etc.
int numberOfColours = 360;
double dR = (tR-fR)/(numberOfColours-1);
double dG = (tG-fG)/(numberOfColours-1);
double dB = (tB-fB)/(numberOfColours-1);
//2.4 loop through adding incrementally different colours
//this is a gradient fromColour --> toColour
for (int n = 0; n < numberOfColours; n++){
[spectrumColours addObject:[UIColor colorWithRed:(fR+n*dR) green:(fG+n*dG) blue:(fB+n*dB) alpha:1.0f]];
}
//3. create a radial image using the spectrum colours
//go through adding the next colour at an increasing angle
//3.1 setup
float radius = MIN(dimension, dimension)/2;
float angle = 2 * M_PI/numberOfColours;
UIBezierPath * bezierPath;
CGPoint center = CGPointMake(dimension/2, dimension/2);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(dimension, dimension), true, 0.0);
UIRectFill(CGRectMake(0, 0, dimension, dimension));
//3.2 loop through pulling the colour and adding
for (int n = 0; n<numberOfColours; n++){
UIColor * colour = spectrumColours[n]; //colour for increment
bezierPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:n * angle endAngle:(n + 1) * angle clockwise:YES];
[bezierPath addLineToPoint:center];
[bezierPath closePath];
[colour setFill];
[colour setStroke];
[bezierPath fill];
[bezierPath stroke];
}
//3.3 create image, add to the radialGradient and end
[radialGradient setImage:UIGraphicsGetImageFromCurrentImageContext()];
UIGraphicsEndImageContext();
//4. create a dot to add to the rotating view
//this covers the connecting line between the two colours
//4.1 set up vars
float containsDots = (M_PI * dimension) /*circumference*/ / lineWidth; //number of dots in circumference
float colourIndex = roundf((numberOfColours / containsDots) * (containsDots-0.5f)); //the nearest colour for the dot
UIColor * closestColour = spectrumColours[(int)colourIndex]; //the closest colour
//4.2 create dot
UIImageView * dot = [UIImageView new];
dot.frame = CGRectMake(dimension-lineWidth, (dimension-lineWidth)/2, lineWidth, lineWidth);
dot.layer.cornerRadius = lineWidth/2;
dot.backgroundColor = closestColour;
[rotateView addSubview:dot];
//5. create the mask
mask = [CAShapeLayer layer];
mask.path = donut.CGPath;
mask.lineWidth = lineWidth;
mask.fillColor = [UIColor clearColor].CGColor;
mask.strokeStart = 0.0f;
mask.strokeEnd = 0.0f;
mask.strokeColor = [UIColor blackColor].CGColor;
mask.lineCap = kCALineCapRound;
//5.1 apply the mask and rotate all by -90 (to move to the 12 position)
clipView.layer.mask = mask;
clipView.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(-90.0f));
}
-(void)animateTo:(float)percentage {
float difference = fabsf(fromPercentage - percentage);
float fixedDuration = difference * duration;
//1. animate stroke End
CABasicAnimation * strokeEndAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
strokeEndAnimation.duration = fixedDuration;
strokeEndAnimation.fromValue = #(fromPercentage);
strokeEndAnimation.toValue = #(percentage);
strokeEndAnimation.fillMode = kCAFillModeForwards;
strokeEndAnimation.removedOnCompletion = false;
strokeEndAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[mask addAnimation:strokeEndAnimation forKey:#"strokeEndAnimation"];
//2. animate rotation of rotateView
CABasicAnimation * viewRotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
viewRotationAnimation.duration = fixedDuration;
viewRotationAnimation.fromValue = #(DEGREES_TO_RADIANS(360 * fromPercentage));
viewRotationAnimation.toValue = #(DEGREES_TO_RADIANS(360 * percentage));
viewRotationAnimation.fillMode = kCAFillModeForwards;
viewRotationAnimation.removedOnCompletion = false;
viewRotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[rotateView.layer addAnimation:viewRotationAnimation forKey:#"viewRotationAnimation"];
//3. update from percentage
fromPercentage = percentage;
}
C. Create view:
Donut * donut = [Donut new];
donut.frame = CGRectMake(20, 100, 140, 140);
donut.baseColour = [[UIColor blackColor] colorWithAlphaComponent:0.2f];
donut.fromColour = [UIColor redColor];
donut.toColour = [UIColor blueColor];
donut.lineWidth = 20.0f;
donut.duration = 2.0f;
[donut layout];
[tasteView addSubview:donut];
D. Animate view:
[donut animateTo:0.5f];
E. Explanation:
The Donut view starts off by creating a base track, clipView, rotateView and a radialGradient imageView. It then calculates 360 colours between the two colours you want to use in the donut. It does so by incrementing the rgb values between the colours. Then a radial gradient image is created using those colours and added to the imageView. Because I wanted to use kCALineCapRound, I added a dot to cover up where the two colours meet. The whole thing needs to be rotated by -90 degrees to put it in the 12 O'Clock position. Then a mask is applied to the view, giving it the donut shape.
As the strokeEnd of the mask is changed, the view beneath it 'rotateView' is rotated as well. This gives the impression that the line is growing / shrinking as long as they in are in sync.
You might also need this:
#define DEGREES_TO_RADIANS(x) (M_PI * (x) / 180.0)
Since your path is a circle, what you are asking for amounts to an angular gradient, that is, a sort of pie that changes color as we sweep a radius round the pie. There is no built-in way to do that, but there's a great library that does it for you:
https://github.com/paiv/AngleGradientLayer
The trick is that you draw your angular gradient with its center at the center of your circle, and then put a mask over it so that it appears only where your circle stroke is supposed to be.
Use below Code. Tested and works in iOS10+
import UIKit
class MMTGradientArcView: UIView {
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay(bounds) } }
var startColor = UIColor.green { didSet { setNeedsDisplay(bounds) } }
var endColor = UIColor.clear { didSet { setNeedsDisplay(bounds) } }
var startAngle:CGFloat = 0 { didSet { setNeedsDisplay(bounds) } }
var endAngle:CGFloat = 360 { didSet { setNeedsDisplay(bounds) } }
override func draw(_ rect: CGRect) {
let gradations = 289 //My School Number
var startColorR:CGFloat = 0
var startColorG:CGFloat = 0
var startColorB:CGFloat = 0
var startColorA:CGFloat = 0
var endColorR:CGFloat = 0
var endColorG:CGFloat = 0
var endColorB:CGFloat = 0
var endColorA:CGFloat = 0
startColor.getRed(&startColorR, green: &startColorG, blue: &startColorB, alpha: &startColorA)
endColor.getRed(&endColorR, green: &endColorG, blue: &endColorB, alpha: &endColorA)
let startAngle:CGFloat = 0
let endAngle:CGFloat = 270
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
var angle = startAngle
for i in 1 ... gradations {
let extraAngle = (endAngle - startAngle) / CGFloat(gradations)
let currentStartAngle = angle
let currentEndAngle = currentStartAngle + extraAngle
let currentR = ((endColorR - startColorR) / CGFloat(gradations - 1)) * CGFloat(i - 1) + startColorR
let currentG = ((endColorG - startColorG) / CGFloat(gradations - 1)) * CGFloat(i - 1) + startColorG
let currentB = ((endColorB - startColorB) / CGFloat(gradations - 1)) * CGFloat(i - 1) + startColorB
let currentA = ((endColorA - startColorA) / CGFloat(gradations - 1)) * CGFloat(i - 1) + startColorA
let currentColor = UIColor.init(red: currentR, green: currentG, blue: currentB, alpha: currentA)
let path = UIBezierPath()
path.lineWidth = lineWidth
path.lineCapStyle = .round
path.addArc(withCenter: center, radius: radius, startAngle: currentStartAngle * CGFloat(Double.pi / 180.0), endAngle: currentEndAngle * CGFloat(Double.pi / 180.0), clockwise: true)
currentColor.setStroke()
path.stroke()
angle = currentEndAngle
}
}
}

Can I add a border to an SKSpriteNode, similar to UIView?

I'm interested if an SKSpriteNode can be made to imitate the behavior of a UIView where I can specify border and corner radius?
self.view.layer.borderColor = [UIColor lightGrayColor].CGColor;
self.view.layer.borderWidth = 2;
self.view.layer.cornerRadius = 2;
self.view.layer.masksToBounds = YES;
The following is a simple, dropin extension for SKSpriteNode that will allow you to draw a border with a given color around your node.
import SpriteKit
extension SKSpriteNode {
func drawBorder(color: UIColor, width: CGFloat) {
let shapeNode = SKShapeNode(rect: frame)
shapeNode.fillColor = .clear
shapeNode.strokeColor = color
shapeNode.lineWidth = width
addChild(shapeNode)
}
}
Not natively. Though you can just add a SKShapeNode as child whose path you create with CGPathCreateWithRoundedRect.
extension SKSpriteNode {
func drawBorder(color: UIColor, width: CGFloat) {
for layer in self.children {
if layer.name == "border" {
layer.removeFromParent()
}
}
let imageSize = self.texture?.size()
let lineWidth = (imageSize!.width / self.size.width) * width
let shapeNode = SKShapeNode(rect: CGRect(x: -imageSize!.width/2, y: -imageSize!.height/2, width: imageSize!.width, height: imageSize!.height))
shapeNode.fillColor = .clear
shapeNode.strokeColor = color
shapeNode.lineWidth = lineWidth
shapeNode.name = "border"
shapeNode.zPosition = 1001
self.addChild(shapeNode)
self.zPosition = 1000
}
}

iOS add / remove shadow from a view

I do not understand how to remove a shadow that was added to a view.
I add to my view in initWithFrame a shadow in this way:
self.layer.borderWidth = 2;
self.layer.borderColor = [UIColor clearColor].CGColor;
self.backgroundColor = [UIColor greenColor];
[self.layer setCornerRadius:8.0f];
CALayer *layer = self.layer;
layer.shadowOffset = CGSizeMake(2, 2);
layer.shadowColor = [[UIColor blackColor] CGColor];
layer.cornerRadius = 8.0f;
layer.shadowRadius = 3.0f;
layer.shadowOpacity = 0.80f;
layer.shadowPath = [[UIBezierPath bezierPathWithRect:layer.bounds] CGPath];
After in the execution of the app I want to remove the shadow from this view. I've tried using:
layer.hidden = YES;
or
self.layer.hidden = YES;
but this hides the view completely, not just the added shadow.
Is there a way to retrieve the added shadow from a view and then hide it?
Thanks!
I guess you could use the shadowOpacity property of your CALayer.
So this should work:
self.layer.shadowOpacity = 0;
See the CALayer's shadowOpacity documentation page
And to show your shadow use:
self.layer.shadowOpacity = 1.0;
Sorry, not sure the correct way, but have you tried changing the properties of the layer shadow? For example, one of these;
layer.shadowOffset = CGSizeMake(0, 0);
layer.shadowColor = [[UIColor clearColor] CGColor];
layer.cornerRadius = 0.0f;
layer.shadowRadius = 0.0f;
layer.shadowOpacity = 0.00f;
Swift 4.2
I am using this in my code for labels and navigation bar.
extension UIView {
func shadow(_ height: Int = 5) {
self.layer.masksToBounds = false
self.layer.shadowRadius = 4
self.layer.shadowOpacity = 1
self.layer.shadowColor = UIColor.gray.cgColor
self.layer.shadowOffset = CGSize(width: 0 , height: height)
}
func removeShadow() {
self.layer.shadowOffset = CGSize(width: 0 , height: 0)
self.layer.shadowColor = UIColor.clear.cgColor
self.layer.cornerRadius = 0.0
self.layer.shadowRadius = 0.0
self.layer.shadowOpacity = 0.0
}
}
I tried the other answers, the only thing that worked for me was to toggle layer.masksToBounds to true/false
lazy var myView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.cornerRadius = 5
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 3
view.layer.shadowOffset = .zero
view.layer.shadowRadius = 5
return view
}()
func showShadow() {
myView.layer.masksToBounds = false
}
func hideShadow() {
myView.layer.masksToBounds = true
}
the "layer" that you are trying to make hidden is the layer of the object that you are having a shadow to it's not a visible aspect.. only the objects with in the layer... it's rather confusing to conceptualize anyways, the only way to remove the shadow is to undo what you originally did, which was suggested above, there is no defined property that you can just toggle a bool and make the shadow go away
Swift 5.+
My solution was to add a shadowBackgroundView, which has a removable shadowLayer. In this way I could easyly remove the layer without resetting the shadow properties.
class ViewController: UIViewController {
private let shadowBackgroundView: UIView = {
let view = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
view.layer.masksToBounds = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(shadowBackgroundView)
// the view you want to add the shadow
let dummyView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
dummyView.backgroundColor = .red
shadowBackgroundView.addSubview(dummyView)
let addShadowButton = UIButton(frame: CGRect(x: 100, y: 300, width: 140, height: 50))
addShadowButton.backgroundColor = .blue
addShadowButton.setTitle("Add Shadow", for: .normal)
addShadowButton.addTarget(self, action: #selector(addShadow), for: .touchUpInside)
let removeShadowButton = UIButton(frame: CGRect(x: 100, y: 450, width: 140, height: 50))
removeShadowButton.backgroundColor = .blue
removeShadowButton.setTitle("Remove Shadow", for: .normal)
removeShadowButton.addTarget(self, action: #selector(removeShadow), for: .touchUpInside)
view.addSubview(addShadowButton)
view.addSubview(removeShadowButton)
}
#objc
func addShadow() {
let shadowLayer = CALayer()
shadowLayer.name = "ShadowLayer"
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOpacity = 1
shadowLayer.shadowOffset = .zero
shadowLayer.shadowRadius = 10
shadowLayer.shadowPath = UIBezierPath(rect: shadowBackgroundView.bounds).cgPath
// Otherwise the shadow will appear above the dummyView
shadowLayer.zPosition = -1
shadowBackgroundView.layer.addSublayer(shadowLayer)
}
#objc
func removeShadow() {
// Alternatively, you could also create the shadowLayer as a property, so you could call shadowLayer.removeFromSuperLayer()
shadowBackgroundView.layer.sublayers?.first { $0.name == "ShadowLayer" }?.removeFromSuperlayer()
}
}
As a Note, for the UITableViewCell, you wouldnt need to add a shadowBackgroundView, but you could add the shadowLayer directly to cell.view.layer, which serves as the backgroundView for the cell.contentView.
Swift 4.2
Just to add to the other answers, you could change the opacity through animation:
#IBAction func btnDidTap(_ sender: UICustomGestureRecognizer) {
guard let view = sender.view else {return}
if sender.state == .began {
UIView.animate(withDuration: 0.3,
animations: {
view.layer.shadowOpacity = 0
})
} else if sender.state == .ended {
UIView.animate(withDuration: 0.3,
animations: {
view.layer.shadowOpacity = 1
})
}
}

Resources