How to draw a rounded rectangle with UIBezierPath? - ios

I'm trying to mask a view with a rounded rectangle UIBezierPath. I want the mask to look exactly the same as if I were just setting layer.cornerRadius:
let frame = CGRect(x: 0, y: 0, width: 80, height: 80)
let cornerRadius = 30
Using cornerRadius:
let view = UIView(frame: frame)
view.layer.cornerRadius = cornerRadius
Using UIBezierPath mask:
let view = UIView(frame: frame)
let maskingShape = CAShapeLayer()
maskingShape.path = UIBezierPath(roundedRect: frame, cornerRadius: cornerRadius).cgPath
view.layer.mask = maskingShape
The resulting rounded rects are completely different. The standard cornerRadius works as expected while the bezier path just snaps to a full circle at a certain radius.
Apparently, this is intended behaviour from iOS 7.
How then do I draw a standard rounded rectangle with a bezier path?
I found this category but this has to be a joke right? Is there no simpler way? :(
Related question.

Related

Invert simple UIView mask (cut hole instead of clip to circle) [duplicate]

This question already has answers here:
How can I 'cut' a transparent hole in a UIImage?
(4 answers)
Closed 1 year ago.
I'm trying to avoid CAShapeLayer because I would need to mess with CABasicAnimation, not UIView.animate. So instead, I'm just using UIView's mask property to mask views. Here's my code currently:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 300))
imageView.image = UIImage(named: "TestImage")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
view.addSubview(imageView)
let maskView = UIView(frame: CGRect(x: 100, y: 100, width: 80, height: 80))
maskView.backgroundColor = UIColor.blue /// ensure opaque
maskView.layer.cornerRadius = 10
imageView.mask = maskView /// set the mask
}
}
Without imageView.mask = maskView
With imageView.mask = maskView
It makes a portion of the image view visible. However, this is what I want:
Instead of making part of the image view visible, how can I cut a hole in it?
You can create an image view and set that as your mask. Note that this does not lend itself to animation. If you want to animate the mask to different shapes, you should add a mask to your view's CALayer and use CALayerAnimation, as you mention. It's not that bad.
Below I outline how to generate an image with a transparent part (a hole) that you can use as a mask in an image view. If your goal is to animate the size, shape, or position of the hole, however, this won't work. You'd have to regenerate the mask image for every frame, which would be really slow.
Here's how you would get the effect your are after for static views using an image view as a mask:
Use UIGraphicsBeginImageContextWithOptions() UIGraphicsImageRenderer to create an image that is opaque for most of your image, and has a transparent "hole" where you want a hole.
Then install that image in your image view, and make that image view your mask.
The code to create a mostly opaque image with a transparent rounded rect "hole" might look like this:
/**
Function to create a UIImage that is mostly opaque, with a transparent rounded rect "knockout" in it. Such an image might be used ask a mask
for another view, where the transparent "knockout" appears as a hole in the view that is being masked.
- Parameter size: The size of the image to create
- Parameter transparentRect: The (rounded )rectangle to make transparent in the middle of the image.
- Parameter cornerRadius: The corner radius ot use in the transparent rectangle. Pass 0 to make the rectangle square-cornered.
*/
func imageWithTransparentRoundedRect(size: CGSize, transparentRect: CGRect, cornerRadius: CGFloat) -> UIImage? {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { (context) in
let frame = CGRect(origin: .zero, size: size)
UIColor.white.setFill()
context.fill(frame)
let roundedRect = UIBezierPath(roundedRect: transparentRect, cornerRadius: cornerRadius)
context.cgContext.setFillColor(UIColor.clear.cgColor)
context.cgContext.setBlendMode(.clear)
roundedRect.fill()
}
return image
}
And a viewDidLoad method that installs a UIImageView with a mask image view with a hole in it might look like this:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .cyan
let size = CGSize(width: 200, height: 300)
let origin = CGPoint(x: 50, y: 50)
let frame = CGRect(origin: origin, size: size)
let imageView = UIImageView(frame: frame)
imageView.image = UIImage(named: "TestImage")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
view.addSubview(imageView)
imageView.layer.borderWidth = 2
//Create a mask image view the same size as the (image) view we will be masking
let maskView = UIImageView(frame: imageView.bounds)
//Build an opaque UIImage with a transparent "knockout" rounded rect inside it.
let transparentRect = CGRect(x: 100, y: 100, width: 80, height: 80)
let maskImage = imageWithTransparentRoundedRect(size: size, transparentRect: transparentRect, cornerRadius: 20)
//Install the image with the "hole" into the mask image view
maskView.image = maskImage
//Make the maskView the ImageView's mask
imageView.mask = maskView /// set the mask
}
}
I created a sample project using the code above. You can download it from Github here:
https://github.com/DuncanMC/UIImageMask.git
I just updated the project to also show how to do the same thing using a CAShapeLayer as a mask on the image view's layer. Doing it that way, it's possible to animate changes to the mask layer's path.
The new version has a segmented control that lets you pick whether to mask the image view using a UIImage in the view's mask property, or via a CAShapeLayer used as a mask on the image view's layer.
For the CAShapeLayer version, the mask layer's path is a rectangle the size of the whole image view, with a second, smaller rounded rectangle drawn inside it. The winding rule on the shape layer is then set to the "even/odd" rule, meaning that if you have to cross an even number of shape boundaries to get to a point, it is considered outside the shape. That enables you to create hollow shapes like we need here.
When you select the layer mask option, it enables an animation button that animates random changes to the "cutout" transparent rectangle in the mask.
The function that creates the mask path looks like this:
func maskPath(transparentRect: CGRect, cornerRadius: CGFloat) -> UIBezierPath {
let fullRect = UIBezierPath(rect: maskLayer.frame)
let roundedRect = UIBezierPath(roundedRect: transparentRect, cornerRadius: cornerRadius)
fullRect.append(roundedRect)
return fullRect
}
And the function that does the animation looks like this:
#IBAction func handleAnimateButton(_ sender: Any) {
//Create a CABasicAnimation that will change the path of our maskLayer
//Use the keypath "path". That tells the animation object what property we are animating
let animation = CABasicAnimation(keyPath: "path")
animation.autoreverses = true //Make the animation reverse back to the oringinal position once it's done
//Use ease-in, ease-out timing, which looks smooth
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = 0.3 //Make each step in the animation last 0.3 seconds.
let transparentRect: CGRect
//Randomly either animate the transparent rect to a different shape or shift it
if Bool.random() {
//Make the transparent rect taller and skinnier
transparentRect = self.transparentRect.inset(by: UIEdgeInsets(top: -20, left: 20, bottom: -20, right: 20))
} else {
//Shift the transparent rect to by a random amount that still says inside the image view's bounds.
transparentRect = self.transparentRect.offsetBy(dx: CGFloat.random(in: -100...20), dy: CGFloat.random(in: -100...100))
}
let cornerRadius: CGFloat = CGFloat.random(in: 0...30)
//install the new path as the animation's `toValue`. If we dont specify a `fromValue` the animation will start from the current path.
animation.toValue = maskPath(transparentRect: transparentRect, cornerRadius: cornerRadius).cgPath
//add the animation to the maskLayer. Since the animation's `keyPath` is "path",
//it will animate the layer's "path" property to the "toValue"
maskLayer.add(animation, forKey: nil)
//Since we don't actually change the path on the mask layer, the mask will revert to it's original path once the animation completes.
}
The results (using my own sample image) look like this:
A sample of the CALayer based mask animation looks like this:

How to apply multiple masks to UIView

I have a question about how to apply multiple masks to a UIView that already has a mask.
The situation:
I have a view with an active mask that creates a hole in its top left corner, this is a template UIView that is reused everywhere in the project. Later in the project I would like to be able to create a second hole but this time in the bottom right corner, this without the need to create a completely new UIView.
The problem:
When I apply the bottom mask, it of course replaces the first one thus removing the top hole ... Is there a way to combine them both? And for that matter to combine any existing mask with a new one?
Thank you in advance!
Based on #Sharad's answer, I realised that re-adding the view's rect would enable me to combine the original and new mask into one.
Here is my solution:
func cutCircle(inView view: UIView, withRect rect: CGRect) {
// Create new path and mask
let newMask = CAShapeLayer()
let newPath = UIBezierPath(ovalIn: rect)
// Create path to clip
let newClipPath = UIBezierPath(rect: view.bounds)
newClipPath.append(newPath)
// If view already has a mask
if let originalMask = view.layer.mask,
let originalShape = originalMask as? CAShapeLayer,
let originalPath = originalShape.path {
// Create bezierpath from original mask's path
let originalBezierPath = UIBezierPath(cgPath: originalPath)
// Append view's bounds to "reset" the mask path before we re-apply the original
newClipPath.append(UIBezierPath(rect: view.bounds))
// Combine new and original paths
newClipPath.append(originalBezierPath)
}
// Apply new mask
newMask.path = newClipPath.cgPath
newMask.fillRule = kCAFillRuleEvenOdd
view.layer.mask = newMask
}
This is code I have used in my project to create one circle and one rectangle mask in UIView, you can replace the UIBezierPath line with same arc code :
func createCircleMask(view: UIView, x: CGFloat, y: CGFloat, radius: CGFloat, downloadRect: CGRect){
self.layer.sublayers?.forEach { ($0 as? CAShapeLayer)?.removeFromSuperlayer() }
let mutablePath = CGMutablePath()
mutablePath.addArc(center: CGPoint(x: x, y: y + radius), radius: radius, startAngle: 0.0, endAngle: 2 * 3.14, clockwise: false)
mutablePath.addRect(view.bounds)
let path = UIBezierPath(roundedRect: downloadRect, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: 5, height: 5))
mutablePath.addPath(path.cgPath)
let mask = CAShapeLayer()
mask.path = mutablePath
mask.fillRule = kCAFillRuleEvenOdd
mask.backgroundColor = UIColor.clear.cgColor
view.layer.mask = mask
}
Pass your same UIView, it removes previous layers and applies new masks on same UIView.
Here mask.fillRule = kCAFillRuleEvenOdd is important. If you notice there are 3 mutablePath.addPath() functions, what kCAFillRuleEvenOdd does is, it first creates a hole with the arc then adds Rect of that view's bound and then another mask to create 2nd hole.
You can do something like the following, if you don't only have "simple shapes" but actual layers from e.g. other views, like UILabel or UIImageView.
let maskLayer = CALayer()
maskLayer.frame = viewToBeMasked.bounds
maskLayer.addSublayer(self.imageView.layer)
maskLayer.addSublayer(self.label.layer)
viewToBeMasked.bounds.layer.mask = maskLayer
So basically I just create a maskLayer, that contains all the other view's layer as sublayer and then use this as a mask.

Add drop blur shadow to circle

Good afternoon,
How do i achieve something like this in swift 3?
circle with blurred drop shadow beneath
The center of the shadow is about 30px from the bottom of the circle. I have tried using the shadow trick but i wasn't able to squish the shadow. I also tried using a picture from photoshop but the blur becomes nasty when scaled up.
let rect = CGRect(x: 0, y: midView.frame.minY, width: (midView.bounds.width), height: 20.0)
let elipticalPath = UIBezierPath(ovalIn: rect).cgPath
let maskLayer = CAGradientLayer()
maskLayer.frame = midView.bounds
maskLayer.shadowRadius = 15
maskLayer.shadowPath = elipticalPath
maskLayer.shadowOpacity = 0.7
maskLayer.shadowOffset = CGSize.zero
maskLayer.shadowColor = UIColor.gray.cgColor
midView.layer.addSublayer(maskLayer)

Add camera layer on irregular shape images IOS

I need to add the camera layer on any irregular shaped image i.e. lets say i have a image which is having irregular shape and inside image there is a circular or any other irregular shape in which i want to embed the live camera.
Any idea how i can achieve this functionality?
You can use UIBezierPath to draw irregular share for a mask CAShapeLayer
let size = 200.0
Create a CAShapeLayer and draw shape in which you wanna embed a cameraPreviewLayer.
let maskLayer = CAShapeLayer()
let maskPath = UIBezierPath()
maskPath.move(to: .zero)
maskPath.addLine(to: CGPoint(x: 10, y: -size))
maskPath.addLine(to: CGPoint(x: size/2, y: -size))
maskPath.addLine(to: CGPoint(x: size*2, y: size))
maskPath.close()
maskLayer.anchorPoint = .zero
Set the mask positon
maskLayer.position = CGPoint(x: 100, y: 400)
maskLayer.path = maskPath.cgPath
self.yourVideoPreviewLayer.mask = maskLayer
self.yourVideoPreviewLayer.masksToBounds = true
Or you can make an image with a shape in which you wanna embed a cameraPreviewLayer. Or if your image's inner shape have an alpha value = 0 you can reverse alpha of your original image and use it as a mask.
let maskLayer = CAShapeLayer()
maskLayer.anchorPoint = .zero
maskLayer.frame = videoPreviewLayer.bounds
maskLayer.contents = YourReversedImage.cgImage
self.videoPreviewLayer.mask = maskLayer
self.videoPreviewLayer.masksToBounds = true
Add additional UIView upon of your UIImageView with same frames(width, height and position). it shouldn't be a subview of UIImageView!
Set background of this UIView to clearColor and create whatever layer you want.
Now you can use this layer as AVCaptureVideoPreviewLayer instead of using UIImageView layers

CALayer does not respect zero shadowRadius while drawing?

It seems that CALayer's property shadowRadius is non-zero while drawing even if explicitelly set to zero when following conditions are met:
shadowPath property is also set on the same CALayer, and
shadowPath set is something else than plain rectangular path
To reproduce the issue I created 2 rounded CALayers with shadow that are identical in everything but shadow path - first one has shadowPath set to nil, second one has shadowPath set to its own shape. I would expect those 2 to render into exactly the same picture but they do not. Here is the result (magnified):
As you can see second rectangle obviously has some shadow radius higher then 0 even though it was set to 0. Here is code used to produce the picture above:
override func viewDidLoad() {
super.viewDidLoad()
let layerWithoutShadowPath = CALayer() //shadow of this rectangle will be drawn correctly
let layerWithShadowPath = CALayer() //shadow of this one will be drawn with radius higher then 0
layerWithoutShadowPath.frame = CGRect(x: 30, y: 30, width: 30, height: 30)
layerWithShadowPath.frame = CGRect(x: 70, y: 30, width: 30, height: 30)
layerWithShadowPath.shadowPath = UIBezierPath(roundedRect: layerWithShadowPath.bounds, cornerRadius: 4.0).CGPath
setupLayer(layerWithoutShadowPath)
setupLayer(layerWithShadowPath)
}
private func setupLayer(layer: CALayer) {
layer.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(1).CGColor
layer.cornerRadius = 4.0
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSize(width: 0, height: 3)
layer.shadowRadius = 0 //SHADOW RADIUS IS SET TO 0 FOR BOTH RECTANGLES
layer.shadowOpacity = 1
view.layer.addSublayer(layer)
}
This might be a Cocoa bug or I am just missing something... Anyway, the question is: How can add rounded rectangle shadow with exactly zero radius to CALayer while shadowPath is set? (if you are wondering why I must set shadowPath the reason is performance)
Well, you might be able to fix it by setting the layer's edgeAntialiasingMask. However, it seems to me that you are needlessly trapped in a world of layer inefficiency - as if the only thing you knew how to do was make the layer draw itself with rounded corners and a shadow. What I would do is draw the yellow rounded square and its shadow as an actual drawing, and make that drawing the content of a layer:
let layer = CALayer()
layer.contentsScale = UIScreen.mainScreen().scale
layer.frame = CGRect(x: 30, y: 30, width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
let con = UIGraphicsGetCurrentContext()
CGContextSetShadowWithColor(con, CGSizeMake(0,3), 1, UIColor.blackColor().CGColor)
let path = UIBezierPath(roundedRect: CGRectMake(0,0,30,30), cornerRadius: 4)
UIColor.yellowColor().setFill()
path.fill()
let im = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
layer.contents = im.CGImage
view.layer.addSublayer(layer)
This has the advantage that the shadow is part of the drawing, and so there is no inefficiency - the very inefficiency you say you are trying to avoid - as there would be if you give the layer itself a shadow and thus compelled the render tree to do the work. Indeed, the same thing is true for the rounded rectangle: it is much more efficient to draw a rounded rectangle, as I am doing here, than to force the render tree to round the layer's corners for you, as you are doing.

Resources