animate along certain path of a layer in swift - swift

I am pretty new to iOS, I am facing a small problem about the CAKeyframeAnimation, I want to animate a view to a certain path of another view layer. it is already successfully animating. However, the position of the animation is not what i expected.
As you can see in my code. I create a UIView(myView) with round bounds. I want another view(square) to follow the orbit of myView's bounds. I already set the myView's centre to the middle of the screen. then I try to get the CGPath of myView and set it to CAKeyframeAnimation's path. However, the square is rotate somewhere else, not on the bounds of myView. Could anyone help me? thanks
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let square = UIView()
square.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
square.backgroundColor = UIColor.redColor()
self.view.addSubview(square)
let bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
let myView = UIView(frame: bounds)
myView.center = self.view.center
myView.layer.cornerRadius = bounds.width/2
myView.layer.borderWidth = 10
myView.layer.borderColor = UIColor.brownColor().CGColor
self.view.addSubview(myView)
var orbit = CAKeyframeAnimation(keyPath: "position")
orbit.path = CGPathCreateWithEllipseInRect(myView.layer.bounds, nil)
orbit.rotationMode = kCAAnimationRotateAuto
orbit.repeatCount = Float.infinity
orbit.duration = 5.0
square.layer.addAnimation(orbit, forKey: "orbit")
}

The frame "describes the view’s location and size in its superview’s coordinate system," whereas bounds "describes the view’s location and size in its own coordinate system."
So if you're building the path from bounds, then square would have to be a subview of myView. If you constructed the path using the frame of myView, then square could be a subview of view.

So, I find another solution, instead of create the CGPath based on some view already existed, I used
let myPath = UIBezierPath(arcCenter: myView.center, radius: bounds.width/2, startAngle: CGFloat(-(CGFloat(M_PI_2))), endAngle: CGFloat((2.0 * M_PI - M_PI_2)), clockwise: true).CGPath
in this way, I can specify the centre point of the UIBezierPath.

Related

How can i achieve this kind of corner redius with shadow view iOS swift?

I am trying to make a design which have top left corner radius and bottom right corner radius with shadow. I am able to make shadow also corner radius around the view.But when i am trying to give corner radius only to side shadow or radius is not showing. Hare what i have done
extension UIview {
//corner radius function
func roundCornersForView(corners:UIRectCorner, radius: CGFloat) {
DispatchQueue.main.async {
let path = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
}
func setShadow(){
self.layer.masksToBounds = false
// set the shadow properties
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 1.0)
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 4.0
self.roundCornersForView(corners: [.topLeft, .bottomRight], radius: 20)
}
}
/// finally call it table cell
cell?.BackView.setShadow()
here is the design what i want to do
1) Why write a separate function to draw rect and then apply cornerRadius mask to your view? Replace the function's contents with:
yourView.layer.masksToBounds = true
yourView.layer.cornerRadius = 20
yourView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]
2) Once you mask your view's corners and set its masksToBounds property to true, you can set shadow to the view's layer and it will automatically wrap around the rounded corners as you desire:-
yourView.layer.shadowOffset = CGSize(width: 0, height: -0.5)
yourView.layer.shadowRadius = 1
yourView.layer.shadowColor = UIColor(red:0.01, green:0.05, blue:0.09, alpha:0.18).cgColor
yourView.layer.shadowOpacity = 0.8
3) It's advised to play with your cell's UI attributes(a subview's cornerRadius and shadow in your case) in the cell class's awakeFromNib() or an init() method rather than in your delegate methods as they get called a lot of times and hence break the whole point of reusability
Have tested the code to apply shadow and it works fine for me. Hope this helps!

Can CAShapeLayer shapes center itself in a subView?

I created an arbitrary view
let middleView = UIView(
frame: CGRect(x: 0.0,
y: view.frame.height/4,
width: view.frame.width,
height: view.frame.height/4))
middleView.backgroundColor = UIColor.blue
view.addSubview(middleView)
Then I created a circle using UIBezierPath; however when I set the position to middleView.center, the circle is far off to the bottom of the view. Can you set the position in the center of a subview?
let shapeLayer = CAShapeLayer()
let circlePath = UIBezierPath(
arcCenter: .zero,
radius: 100,
startAngle: CGFloat(0).toRadians(),
endAngle: CGFloat(360).toRadians(),
clockwise: true)
shapeLayer.path = circlePath.cgPath
shapeLayer.strokeColor = UIColor.purple.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.position = middleView.center
middleView.layer.addSublayer(shapeLayer)
How do I center this circle in that view?
You have two problems.
First, you are setting shapeLayer.position = middleView.center. The center of a view is is the superview's geometry. In other words, middleView.center is relative to view, not to middleView. But then you're adding shapeLayer as a sublayer of middleView.layer, which means shapeLayer needs a position that is in middleView's geometry, not in view's geometry. You need to set shapeLayer.position to the center of middleView.bounds:
shapeLayer.position = CGPoint(x: middleView.bounds.midX, y: middleView.bounds.midY)
Second, you didn't say where you're doing all this. My guess is you're doing it in viewDidLoad. But that is too early. In viewDidLoad, the views loaded from the storyboard still have the frames they were given in the storyboard, and haven't been laid out for the current device's screen size yet. So it's a bad idea to look at frame (or bounds or center) in viewDidLoad if you don't do something to make sure that things will be laid out correctly during the layout phase. Usually you do this by setting the autoresizingMask or creating constraints. Example:
let middleView = UIView(
frame: CGRect(x: 0.0,
y: view.frame.height/4,
width: view.frame.width,
height: view.frame.height/4))
middleView.backgroundColor = UIColor.blue
middleView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleBottomMargin]
view.addSubview(middleView)
However, shapeLayer doesn't belong to a view, so it doesn't have an autoresizingMask and can't be constrained. You have to lay it out in code. You could do that, but it's better to just use a view to manage the shape layer. That way, you can use autoresizingMask or constraints to control the layout of the shape, and you can set it up in viewDidLoad.
let circleView = CircleView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
circleView.center = CGPoint(x: middleView.bounds.midX, y: middleView.bounds.midY)
circleView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
circleView.shapeLayer.strokeColor = UIColor.purple.cgColor
circleView.shapeLayer.fillColor = nil
middleView.addSubview(circleView)
...
class CircleView: UIView {
override class var layerClass: AnyClass { return CAShapeLayer.self }
var shapeLayer: CAShapeLayer { return layer as! CAShapeLayer }
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.path = UIBezierPath(ovalIn: bounds).cgPath
}
}
Result:
And after rotating to landscape:

CABasicAnimation on transform.scale translates CAShapeLayer on the X & Y axis

I am trying to add a pulsating effect around a button, however, the code I am using translates the CAShapeLayer as well as increasing its size.
How do I only increase the scale of a CAShapeLayer during this animation whilst keeping its position in the view static?
I have isolated the code out into a simple project which performs this animation and it is still occurring.
See effect in a video here: https://imgur.com/a/AbTtLKe
To test this:
Create a new project
Add a button into the centre of the view
Link it to the viewControllers code file as an IBOutlet with the name beginButton
Here is my code:
let pulsatingLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
let circularPath = UIBezierPath(arcCenter: beginButton.center, radius: beginButton.bounds.midX, startAngle: -CGFloat.pi / 2, endAngle: 2 * .pi, clockwise: true)
pulsatingLayer.path = circularPath.cgPath
pulsatingLayer.strokeColor = UIColor.clear.cgColor
pulsatingLayer.lineWidth = 10
pulsatingLayer.fillColor = UIColor.red.cgColor
pulsatingLayer.lineCap = kCALineCapRound
view.layer.addSublayer(pulsatingLayer)
animatePulsatingLayer()
}
private func animatePulsatingLayer() {
let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.toValue = 1.5
pulseAnimation.duration = 1
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = Float.infinity
pulsatingLayer.add(pulseAnimation, forKey: "pulsing")
}
Thanks!
Your animation is relative to the origin of the frame of the view.
By changing the center of the circular path to be CGPoint.zero, you get an animation that pulses centered on the origin of the layer. Then by adding that to a new pulsatingView whose origin is centered on the button, the pulsing layer is centered on the button.
override func viewDidLoad() {
super.viewDidLoad()
let circularPath = UIBezierPath(arcCenter: CGPoint.zero, radius: beginButton.bounds.midX, startAngle: -CGFloat.pi / 2, endAngle: 2 * .pi, clockwise: true)
pulsatingLayer.path = circularPath.cgPath
pulsatingLayer.strokeColor = UIColor.clear.cgColor
pulsatingLayer.lineWidth = 10
pulsatingLayer.fillColor = UIColor.red.cgColor
pulsatingLayer.lineCap = kCALineCapRound
let pulsatingView = UIView(frame: .zero)
view.addSubview(pulsatingView)
view.bringSubview(toFront: beginButton)
// use Auto Layout to place the new pulsatingView relative to the button
pulsatingView.translatesAutoresizingMaskIntoConstraints = false
pulsatingView.leadingAnchor.constraint(equalTo: beginButton.centerXAnchor).isActive = true
pulsatingView.topAnchor.constraint(equalTo: beginButton.centerYAnchor).isActive = true
pulsatingView.layer.addSublayer(pulsatingLayer)
animatePulsatingLayer()
}
You need to read up on transformation matrixes. (Any book on 3D computer graphics should have a section that covers it.)
A scale transformation is centered on the current origin. So if your shape is not centered on the origin, it will be drawn in towards the origin. To scale a shape in toward it's own center you need to do something like this:
Create an identity transform
Translate it by (-x, -y) of your shape's center
Add the desired scale to the transform
Add a Translate by (x, y) to shift the shape back
Concat your transform to the layer's transform.
(I always have to think really hard to get this stuff right. I wrote the above off the top of my head, before 7:00 AM local time on a weekend, without sufficient caffeine. It probably isn't exactly right, but should give you the idea.)

Cut a circle out of a UIView using mask [duplicate]

This question already has answers here:
How can I 'cut' a transparent hole in a UIImage?
(4 answers)
Closed 6 years ago.
In my app I have a square UIView and I want to cut a hole/notch out of the top of. All the tutorials online are all the same and seemed quite straightforward but every single one of them always delivered the exact opposite of what I wanted.
For example this is the code for the custom UIView:
class BottomOverlayView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawCircle()
}
fileprivate func drawCircle(){
let circleRadius: CGFloat = 80
let topMidRectangle = CGRect(x: 0, y: 0, width: circleRadius*2, height: circleRadius*2)
let circle: CAShapeLayer = CAShapeLayer()
circle.position = CGPoint(x: (frame.width/2)-circleRadius, y: 0-circleRadius)
circle.fillColor = UIColor.black.cgColor
circle.path = UIBezierPath(ovalIn: topMidRectangle).cgPath
circle.fillRule = kCAFillRuleEvenOdd
self.layer.mask = circle
self.clipsToBounds = true
}
}
Here is what I hope to achieve (the light blue is the UIView, the dark blue is the background):
But here is what I get instead. (Every single time no matter what I try)
I'm not sure how I would achieve this, aside from making a mask that is already the exact shape that I need. But if I was able to do that then I wouldn't be having this issue in the first place. Does anyone have any tips on how to achieve this?
EDIT: The question that this is supposedly a duplicate of I had already attempted and was not able to get working. Perhaps I was doing it wrong or using it in the wrong context. I wasn't familiar with any of the given methods and also the use of pointers made it seem a bit outdated. The accepted answer does a much better job of explaining how this can be implemented using much more widely used UIBezierPaths and also within the context of a custom UIView.
I'd suggest drawing a path for your mask, e.g. in Swift 3
// BottomOverlayView.swift
import UIKit
#IBDesignable
class BottomOverlayView: UIView {
#IBInspectable
var radius: CGFloat = 100 { didSet { updateMask() } }
override func layoutSubviews() {
super.layoutSubviews()
updateMask()
}
private func updateMask() {
let path = UIBezierPath()
path.move(to: bounds.origin)
let center = CGPoint(x: bounds.midX, y: bounds.minY)
path.addArc(withCenter: center, radius: radius, startAngle: .pi, endAngle: 0, clockwise: false)
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.close()
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
Note, I tweaked this to set the mask in two places:
From layoutSubviews: That way if the frame changes, for example as a result of auto layout (or by manually changing the frame or whatever), it will update accordingly; and
If you update radius: That way, if you're using this in a storyboard or if you change the radius programmatically, it will reflect that change.
So, you can overlay a half height, light blue BottomOverlayView on top of a dark blue UIView, like so:
That yields:
If you wanted to use the "cut a hole" technique suggested in the duplicative answer, the updateMask method would be:
private func updateMask() {
let center = CGPoint(x: bounds.midX, y: bounds.minY)
let path = UIBezierPath(rect: bounds)
path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
let mask = CAShapeLayer()
mask.fillRule = .evenOdd
mask.path = path.cgPath
layer.mask = mask
}
I personally find the path within a path with even-odd rule to be a bit counter-intuitive. Where I can (such as this case), I just prefer to just draw the path of the mask. But if you need a mask that has a cut-out, this even-odd fill rule approach can be useful.

Swift - How to create a view with a shape cropped in it

I'm trying to achieve the result shown in the image using swift 1.2 and xcode 6.
Basically I want to create a view with a shape cut in it to be able to see the the view below to make a tutorial for my app.
I know how to create a circular shape but i don't know how to cut it out in a view.
I need a complete example on how to do it please.
Thanks in advance
Even though there is an answer, i'd like to share my way:
// Let's say that you have an outlet to the image view called imageView
// Create the white view
let whiteView = UIView(frame: imageView.bounds)
let maskLayer = CAShapeLayer() //create the mask layer
// Set the radius to 1/3 of the screen width
let radius : CGFloat = imageView.bounds.width/3
// Create a path with the rectangle in it.
let path = UIBezierPath(rect: imageView.bounds)
// Put a circle path in the middle
path.addArcWithCenter(imageView.center, radius: radius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: true)
// Give the mask layer the path you just draw
maskLayer.path = path.CGPath
// Fill rule set to exclude intersected paths
maskLayer.fillRule = kCAFillRuleEvenOdd
// By now the mask is a rectangle with a circle cut out of it. Set the mask to the view and clip.
whiteView.layer.mask = maskLayer
whiteView.clipsToBounds = true
whiteView.alpha = 0.8
whiteView.backgroundColor = UIColor.whiteColor()
//If you are in a VC add to the VC's view (over the image)
view.addSubview(whiteView)
// Annnnnd you're done.
//assume you create a UIImageView and content image before execute this code
let sampleMask = UIView()
sampleMask.frame = self.view.frame
sampleMask.backgroundColor = UIColor.black.withAlphaComponent(0.6)
//assume you work in UIViewcontroller
self.view.addSubview(sampleMask)
let maskLayer = CALayer()
maskLayer.frame = sampleMask.bounds
let circleLayer = CAShapeLayer()
//assume the circle's radius is 150
circleLayer.frame = CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height)
let finalPath = UIBezierPath(roundedRect: CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(ovalIn: CGRect(x:sampleMask.center.x - 150, y:sampleMask.center.y - 150, width: 300, height: 300))
finalPath.append(circlePath.reversing())
circleLayer.path = finalPath.cgPath
circleLayer.borderColor = UIColor.white.withAlphaComponent(1).cgColor
circleLayer.borderWidth = 1
maskLayer.addSublayer(circleLayer)
sampleMask.layer.mask = maskLayer
Here is sample code for how you can make a circle Mask for a UIView:
let sampleView = UIView(frame: UIScreen.mainScreen().bounds)
let maskLayer = CALayer()
maskLayer.frame = sampleView.bounds
let circleLayer = CAShapeLayer()
//assume the circle's radius is 100
circleLayer.frame = CGRectMake(sampleView.center.x - 100, sampleView.center.y - 100, 200, 200)
let circlePath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 200, 200))
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = UIColor.blackColor().CGColor
maskLayer.addSublayer(circleLayer)
sampleView.layer.mask = maskLayer
Here is what I made in the playground:
The easiest way to do this would be to create a png image with partly transparent white around the outside and a clear circle in the middle. Then stack 2 image views on top of each other, with the masking image on top, and set its "opaque" flag to false.
You could also do this by creating a CAShapeLayer and set it up to use a translucent white color, then install a shape that is the square with the hole cut out of it shape. You'd install that shape layer on top of your image view's layer.
The most general-purpose way to do that would be to create a custom subclass of UIImageView and have the init method of your subclass create and install the shape layer. I just created a gist yesterday that illustrated creating a custom subclass of UIImageView. Here is the link: ImageViewWithGradient gist
That gist creates a gradient layer. It would be a simple matter to adapt it to create a shape layer instead, and if you modified the layoutSubviews method you could make it adapt the view and path if the image view gets resized.
EDIT:
Ok, I took the extra step of creating a playground that creates a cropping image view. You can find that at ImageViewWithMask on github
The resulting image for my playground looks like this:
class MakeTransparentHoleOnOverlayView: UIView {
#IBOutlet weak var transparentHoleView: UIView!
// MARK: - Drawing
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.transparentHoleView != nil {
// Ensures to use the current background color to set the filling color
self.backgroundColor?.setFill()
UIRectFill(rect)
let layer = CAShapeLayer()
let path = CGMutablePath()
// Make hole in view's overlay
// NOTE: Here, instead of using the transparentHoleView UIView we could use a specific CFRect location instead...
path.addRect(transparentHoleView.frame)
path.addRect(bounds)
layer.path = path
layer.fillRule = kCAFillRuleEvenOdd
self.layer.mask = layer
}
}
override func layoutSubviews () {
super.layoutSubviews()
}
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
}