Aligning CAShapeLayer center of my UIView - ios

I've been trying to solve this for days, and none of the suggestions solved my problem. I have a UIView inside a UITableView. I've been trying to draw my CAShapeLayer inside my UIView, but I just can't get it right.
I need my yellow CAShapeLayer to be exactly center within the gray UIView.
func DrawActivityRect(cell: CalorieDashboardTVCell){
let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)
let trackLayer = CAShapeLayer()
trackLayer.frame = cell.calorieBurnUIView.bounds
trackLayer.path = rectangle.cgPath
trackLayer.position = cell.calorieBurnUIView.center
trackLayer.strokeColor = UIColor.yellow.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
cell.calorieBurnUIView.layer.addSublayer(trackLayer)
}
Result:

I suspect the cell size change after you have set the layer. The easiest place to fix this is in the cell's layoutSubviews(). Since your path is using absolute coordinates you need to update both the layer frame and the path.
override func layoutSubviews() {
super.layoutSubviews()
// You need to keep trackLayer around after you created it
let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)
self.trackLayer.frame = cell.calorieBurnUIView.bounds
self.trackLayer.path = rectangle.cgPath
self.trackLayer.position = cell.calorieBurnUIView.center
}

Related

How to make an UIView into circle shape in swift 4.2?

The width(40) and height(40) of the UIView are equal.
I have tried these but they didn't work for me:
countView?.clipsToBounds = true
self.countView?.layer.cornerRadius = min((countView?.frame.size.width)!, (countView?.frame.size.height)!)/2
and also
self.countView.layer.cornerRadius = (countView.frame.size.width)/2
Thanks
In addition to #Stephan answer.
With less code:
self.countView.layer.cornerRadius = self.countView.bounds.height / 2
Result:
You can use a mask layer like this:
override func viewDidLoad() {
super.viewDidLoad()
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(ovalIn: self.countView.bounds).cgPath;
self.countView.layer.mask = maskLayer
}
Example Output
Here the output of a UIView with width/height = 128/128:

Creating a shadow for a UIImageView that has rounded corners?

I am trying to create an ImageView that has rounded corners and a shadow to give it some depth. I was able to create a shadow for the UIImageView, but whenever I added the code to also make it have rounded corners, it only had rounded corners with no shadow. I have an IBOutlet named myImage, and it is inside of the viewDidLoad function. Does anybody have any ideas on how to make it work? What am I doing wrong?
override func viewDidLoad() {
super.ViewDidLoad()
myImage.layer.shadowColor = UIColor.black.cgColor
myImage.layer.shadowOpacity = 1
myImage.layer.shadowOffset = CGSize.zero
myImage.layer.shadowRadius = 10
myImage.layer.shadowPath = UIBezierPath(rect: myImage.bounds).cgPath
myImage.layer.shouldRasterize = false
myImage.layer.cornerRadius = 10
myImage.clipsToBounds = true
}
If you set clipsToBounds to true, this will round the corners but prevent the shadow from appearing. In order to resolve this, you can create two views. The container view should have the shadow, and its subview should have the rounded corners.
The container view has clipsToBounds set to false, and has the shadow properties applied. If you want the shadow to be rounded as well, use the UIBezierPath constructor that takes in a roundedRect and cornerRadius.
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
outerView.clipsToBounds = false
outerView.layer.shadowColor = UIColor.black.cgColor
outerView.layer.shadowOpacity = 1
outerView.layer.shadowOffset = CGSize.zero
outerView.layer.shadowRadius = 10
outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: 10).cgPath
Next, set the image view (or any other type of UIView) to be the same size of the container view, set clipsToBounds to true, and give it a cornerRadius.
let myImage = UIImageView(frame: outerView.bounds)
myImage.clipsToBounds = true
myImage.layer.cornerRadius = 10
Finally, remember to make the image view a subview of the container view.
outerView.addSubview(myImage)
The result should look something like this:
Swift 5:
You can use the below extension:
extension UIImageView {
func applyshadowWithCorner(containerView : UIView, cornerRadious : CGFloat){
containerView.clipsToBounds = false
containerView.layer.shadowColor = UIColor.black.cgColor
containerView.layer.shadowOpacity = 1
containerView.layer.shadowOffset = CGSize.zero
containerView.layer.shadowRadius = 10
containerView.layer.cornerRadius = cornerRadious
containerView.layer.shadowPath = UIBezierPath(roundedRect: containerView.bounds, cornerRadius: cornerRadious).cgPath
self.clipsToBounds = true
self.layer.cornerRadius = cornerRadious
}
}
How to use:
Drag a UIView on the storyboard
Drag an ImageView inside that UIView
Storyboard should look like this:
Create IBOutlet for both Views, call extension on your ImageView, and pass above created UIView as an argument.
Here is the output :
Finally here is how to
Properly have an image view, with rounded corners AND shadows.
It's this simple:
First some bringup code ..
class ShadowRoundedImageView: UIView {
override init(frame: CGRect) {
super.init(frame: frame); common() }
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder); common() }
private func common() {
backgroundColor = .clear
clipsToBounds = false
self.layer.addSublayer(shadowLayer)
self.layer.addSublayer(imageLayer) // (in that order)
}
#IBInspectable var image: UIImage? = nil {
didSet {
imageLayer.contents = image?.cgImage
shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath
}
}
and then the layers ...
var imageLayer: CALayer = CALayer()
var shadowLayer: CALayer = CALayer()
var shape: UIBezierPath {
return UIBezierPath(roundedRect: bounds, cornerRadius:50)
}
var shapeAsPath: CGPath {
return shape.cgPath
}
var shapeAsMask: CAShapeLayer {
let s = CAShapeLayer()
s.path = shapeAsPath
return s
}
override func layoutSubviews() {
super.layoutSubviews()
imageLayer.frame = bounds
imageLayer.contentsGravity = .resizeAspectFill // (as preferred)
imageLayer.mask = shapeAsMask
shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath
shadowLayer.shadowOpacity = 0.80 // etc ...
}
}
Here is the
Explanation
UIImageView is useless, you use a UIView
You need two layers, one for the shadow and one for the image
To round an image layer you use a mask
To round a shadow layer you use a path
For the shadow qualities, obviously add code as you see fit
shadowLayer.shadowOffset = CGSize(width: 0, height: 20)
shadowLayer.shadowColor = UIColor.purple.cgColor
shadowLayer.shadowRadius = 5
shadowLayer.shadowOpacity = 0.80
For the actual shape (the bez path) make it any shape you wish.
(For example this tip https://stackoverflow.com/a/41553784/294884 shows how to make only one or two corners rounded.)
Summary:
• Use two layers on a UIView
Make your bezier and ...
• Use a mask on the image layer
• Use a path on the shadow layer
Here is a another solution (tested code) in swift 2.0
If you set clipsToBounds to true, this will round the corners but prevent the shadow from appearing. So, you can add same size UIView in storyboard behind imageview and we can give shadow to that view
SWIFT 2.0
outerView.layer.cornerRadius = 20.0
outerView.layer.shadowColor = UIColor.blackColor().CGColor
outerView.layer.shadowOffset = CGSizeMake(0, 2)
outerView.layer.shadowOpacity = 1
outerView.backgroundColor = UIColor.whiteColor()
You can use a simple class I have created to add image with rounded corners and shadow directly from Storyboard
You can find the class here

How to remove CALayer mask margin? + how to position UILabel properly?

I am trying to create the effect of the text color inversing while being intercepted by the background layer.
As you can see in the screenshot below, i have a blue CAShapeLayer moving from left to right and a mask layer directly attached to it, moving accordingly. Strangely there is a gap between the two layers.
My Code for the layers:
//Add Shape Layer
let path = UIBezierPath(rect: self.contentView.frame)
initPostion = -contentView.frame.size.width+initialVisibility
colorStripeLayer.path = path.CGPath
colorStripeLayer.fillColor = UIColor(red:0.71, green:0.86, blue:0.84, alpha:1.0).CGColor
colorStripeLayer.frame = self.contentView.frame
colorStripeLayer.transform = CATransform3DMakeTranslation(initPostion, 0, 0)
self.contentView.layer.insertSublayer(colorStripeLayer, atIndex: 0)
//white UILabel Masking
maskLayer.path = path.CGPath
maskLayer.fillColor = UIColor.lightGrayColor().CGColor
maskLayer.frame = self.contentView.bounds
Additionaly I wanted to place the white text exactly underneath the black one, but even after setting all the attributes, it still positions quite randomly.
Code for the labels:
textLabel?.layer.mask = maskLayer
textLabel?.backgroundColor = UIColor.clearColor()
textLabel?.textColor = UIColor.blackColor()
let whiteLabel = UILabel(frame: textLabel!.frame)
whiteLabel.text = textLabel!.text
whiteLabel.font = textLabel!.font
whiteLabel.textAlignment = textLabel!.textAlignment
whiteLabel.textColor = UIColor.whiteColor()
contentView.insertSubview(whiteLabel, belowSubview: textLabel!)
Animation is just a simple x-axis translation, done in pop.
Can anyone help here?
2 Problems here

Drawing sublayers inside a bezier Arc

I'm trying to draw a series of vertical lines inside of an arc but I'm having trouble being able to do this. I'm trying to do this using CAShapeLayers The end result is something that looks like this.
I know how to draw the curved arc and the line segments using CAShapeLayers but what I can't seem to figure out is how to draw the vertical lines inside the CAShapeLayer
My initial approach is to subclass CAShapeLayer and in the subclass, attempt to draw the vertical lines. However, I'm not getting the desired results. Here is my code for adding a line to a bezier point and attempting to add the sub layers.
class CustomLayer : CAShapeLayer {
override init() {
super.init()
}
func drawDividerLayer(){
print("Init has been called in custom layer")
print("The bounds of the custom layer is: \(bounds)")
print("The frame of the custom layer is: \(frame)")
let bezierPath = UIBezierPath()
let dividerShapeLayer = CAShapeLayer()
dividerShapeLayer.strokeColor = UIColor.redColor().CGColor
dividerShapeLayer.lineWidth = 1
let startPoint = CGPointMake(5, 0)
let endPoint = CGPointMake(5, 8)
let convertedStart = convertPoint(startPoint, toLayer: dividerShapeLayer)
let convertedEndPoint = convertPoint(endPoint, toLayer: dividerShapeLayer)
bezierPath.moveToPoint(convertedStart)
bezierPath.addLineToPoint(convertedEndPoint)
dividerShapeLayer.path = bezierPath.CGPath
addSublayer(dividerShapeLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class DrawView : UIView {
var customDrawLayer : CAShapeLayer!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//drawLayers()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
func drawLayers() {
let bezierPath = UIBezierPath()
let startPoint = CGPointMake(5, 35)
let endPoint = CGPointMake(100, 35)
bezierPath.moveToPoint(startPoint)
bezierPath.addLineToPoint(endPoint)
let customLayer = CustomLayer()
customLayer.frame = CGPathGetBoundingBox(bezierPath.CGPath)
customLayer.drawDividerLayer()
customLayer.strokeColor = UIColor.blackColor().CGColor
customLayer.opacity = 0.5
customLayer.lineWidth = 8
customLayer.fillColor = UIColor.clearColor().CGColor
layer.addSublayer(customLayer)
customLayer.path = bezierPath.CGPath
}
However this code produces this image:
It definitely seems that I have a coordinate space problem/bounds/frame issue but I'm not quite sure. The way I want this to work is to draw from the top of the superLayer to the bottom of the superLayer inside of the CustomLayer class. But not only that, this must work using the bezier path addArcWithCenter: method which I haven't gotten to yet because I'm trying to solve this problem first. Any help would be appreciated.
The easiest way to draw an arc that consists of lines is to use lineDashPattern:
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)
let arc = CAShapeLayer()
arc.path = path.CGPath
arc.lineWidth = 50
arc.lineDashPattern = [4,15]
arc.strokeColor = UIColor.lightGrayColor().CGColor
arc.fillColor = UIColor.clearColor().CGColor
view.layer.addSublayer(arc)
So this is a blue arc underneath the dashed arc shown above. Obviously, I enlarged it for the sake of visibility, but it illustrates the idea.

How to add shadow to ImageView? [duplicate]

I am trying to create an ImageView that has rounded corners and a shadow to give it some depth. I was able to create a shadow for the UIImageView, but whenever I added the code to also make it have rounded corners, it only had rounded corners with no shadow. I have an IBOutlet named myImage, and it is inside of the viewDidLoad function. Does anybody have any ideas on how to make it work? What am I doing wrong?
override func viewDidLoad() {
super.ViewDidLoad()
myImage.layer.shadowColor = UIColor.black.cgColor
myImage.layer.shadowOpacity = 1
myImage.layer.shadowOffset = CGSize.zero
myImage.layer.shadowRadius = 10
myImage.layer.shadowPath = UIBezierPath(rect: myImage.bounds).cgPath
myImage.layer.shouldRasterize = false
myImage.layer.cornerRadius = 10
myImage.clipsToBounds = true
}
If you set clipsToBounds to true, this will round the corners but prevent the shadow from appearing. In order to resolve this, you can create two views. The container view should have the shadow, and its subview should have the rounded corners.
The container view has clipsToBounds set to false, and has the shadow properties applied. If you want the shadow to be rounded as well, use the UIBezierPath constructor that takes in a roundedRect and cornerRadius.
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
outerView.clipsToBounds = false
outerView.layer.shadowColor = UIColor.black.cgColor
outerView.layer.shadowOpacity = 1
outerView.layer.shadowOffset = CGSize.zero
outerView.layer.shadowRadius = 10
outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: 10).cgPath
Next, set the image view (or any other type of UIView) to be the same size of the container view, set clipsToBounds to true, and give it a cornerRadius.
let myImage = UIImageView(frame: outerView.bounds)
myImage.clipsToBounds = true
myImage.layer.cornerRadius = 10
Finally, remember to make the image view a subview of the container view.
outerView.addSubview(myImage)
The result should look something like this:
Swift 5:
You can use the below extension:
extension UIImageView {
func applyshadowWithCorner(containerView : UIView, cornerRadious : CGFloat){
containerView.clipsToBounds = false
containerView.layer.shadowColor = UIColor.black.cgColor
containerView.layer.shadowOpacity = 1
containerView.layer.shadowOffset = CGSize.zero
containerView.layer.shadowRadius = 10
containerView.layer.cornerRadius = cornerRadious
containerView.layer.shadowPath = UIBezierPath(roundedRect: containerView.bounds, cornerRadius: cornerRadious).cgPath
self.clipsToBounds = true
self.layer.cornerRadius = cornerRadious
}
}
How to use:
Drag a UIView on the storyboard
Drag an ImageView inside that UIView
Storyboard should look like this:
Create IBOutlet for both Views, call extension on your ImageView, and pass above created UIView as an argument.
Here is the output :
Finally here is how to
Properly have an image view, with rounded corners AND shadows.
It's this simple:
First some bringup code ..
class ShadowRoundedImageView: UIView {
override init(frame: CGRect) {
super.init(frame: frame); common() }
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder); common() }
private func common() {
backgroundColor = .clear
clipsToBounds = false
self.layer.addSublayer(shadowLayer)
self.layer.addSublayer(imageLayer) // (in that order)
}
#IBInspectable var image: UIImage? = nil {
didSet {
imageLayer.contents = image?.cgImage
shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath
}
}
and then the layers ...
var imageLayer: CALayer = CALayer()
var shadowLayer: CALayer = CALayer()
var shape: UIBezierPath {
return UIBezierPath(roundedRect: bounds, cornerRadius:50)
}
var shapeAsPath: CGPath {
return shape.cgPath
}
var shapeAsMask: CAShapeLayer {
let s = CAShapeLayer()
s.path = shapeAsPath
return s
}
override func layoutSubviews() {
super.layoutSubviews()
imageLayer.frame = bounds
imageLayer.contentsGravity = .resizeAspectFill // (as preferred)
imageLayer.mask = shapeAsMask
shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath
shadowLayer.shadowOpacity = 0.80 // etc ...
}
}
Here is the
Explanation
UIImageView is useless, you use a UIView
You need two layers, one for the shadow and one for the image
To round an image layer you use a mask
To round a shadow layer you use a path
For the shadow qualities, obviously add code as you see fit
shadowLayer.shadowOffset = CGSize(width: 0, height: 20)
shadowLayer.shadowColor = UIColor.purple.cgColor
shadowLayer.shadowRadius = 5
shadowLayer.shadowOpacity = 0.80
For the actual shape (the bez path) make it any shape you wish.
(For example this tip https://stackoverflow.com/a/41553784/294884 shows how to make only one or two corners rounded.)
Summary:
• Use two layers on a UIView
Make your bezier and ...
• Use a mask on the image layer
• Use a path on the shadow layer
Here is a another solution (tested code) in swift 2.0
If you set clipsToBounds to true, this will round the corners but prevent the shadow from appearing. So, you can add same size UIView in storyboard behind imageview and we can give shadow to that view
SWIFT 2.0
outerView.layer.cornerRadius = 20.0
outerView.layer.shadowColor = UIColor.blackColor().CGColor
outerView.layer.shadowOffset = CGSizeMake(0, 2)
outerView.layer.shadowOpacity = 1
outerView.backgroundColor = UIColor.whiteColor()
You can use a simple class I have created to add image with rounded corners and shadow directly from Storyboard
You can find the class here

Resources