CALayer does not respect zero shadowRadius while drawing? - ios

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.

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:

SceneKit CALayer unsharp drawing

I'm trying to draw UIBezierPaths and display them on a SCNPlane, though I'm getting a very unsharp result (See in the image) How could I make it sharper?
let displayLayer = CAShapeLayer()
displayLayer.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
displayLayer.path = path.cgPath
displayLayer.fillColor = UIColor.clear.cgColor
displayLayer.strokeColor = stroke.cgColor
displayLayer.lineWidth = lineWidth
let plane = SCNPlane(width:size.width, height: size.height)
let material = SCNMaterial()
material.diffuse.contents = displayLayer
plane.materials = [material]
let node = SCNNode(geometry: plane)
I've tried to increase the displayLayer.frame's size but it only made things smaller.
Thanks for your answer!
Andras
This has been driving me crazy, so hopefully this answer helps someone else who stumbles across this. I'm mapping a CALayer to a SCNMaterial texture for use in an ARKit scene, and everything was blurry/pixelated. Setting the contentsScale property of the CALayer to UIScreen.main.scale didn't do anything, nor playing with shouldRasterize and rasterizationScale.
The solution is to set the layer's frame to the desired frame, multiplied by the screen's scale, otherwise the material is scale transforming the layer to fit the texture. In other words, the layer's size needs to be 3x its desired size.
let layer = CALayer()
layer.frame = CGRect(x: 0, y: 0, width: 500 * UIScreen.main.scale, height: 750 * UIScreen.main.scale)
Try to change UIBezierPath "flatness" property (0.1, 0.01, 0.001 etc).

How to draw a rounded rectangle with UIBezierPath?

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.

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)

Using drawRect to draw & animate two graphs. A background graph, and a foreground graph

I am using drawRect to draw a pretty simple shape (dark blue in the image below).
I'd like this to animate from the left to the right, so that it grows. The caveat here is I need there to be a "max" background in gray, as seen in the top part of the image.
Right now, I'm simulating this animation by overlaying a white view, and then animating the size of it, so that it looks like the blue is animating to the right. While this works... I need the background gray shape to always be there. With my overlayed white view, this just doesn't work.
Here's the code for drawing the "current code" version:
let context = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(context, 0, self.bounds.height - 6)
CGContextAddLineToPoint(context, self.bounds.width, 0)
CGContextAddLineToPoint(context, self.bounds.width, self.bounds.height)
CGContextAddLineToPoint(context, 0, self.bounds.height)
CGContextSetFillColorWithColor(context,UIColor(red: 37/255, green: 88/255, blue: 120/255, alpha: 1.0).CGColor)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
How can I animate the blue part from left to right, while keeping the gray "max" portion of the graph always visible?
drawRect is producing still picture. To get animation you're saying about I'd recommend the following:
Use CoreAnimation to produce animation
Use UIBezierPath to make a shape you need
Use CALayer's mask to animate within required shape
Here is example code for Playground:
import UIKit
import QuartzCore
import XCPlayground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
XCPlaygroundPage.currentPage.liveView = view
let maskPath = UIBezierPath()
maskPath.moveToPoint(CGPoint(x: 10, y: 30))
maskPath.addLineToPoint(CGPoint(x: 10, y: 25))
maskPath.addLineToPoint(CGPoint(x: 100, y: 10))
maskPath.addLineToPoint(CGPoint(x: 100, y: 30))
maskPath.closePath()
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.whiteColor().CGColor
let rectToAnimateFrom = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 97, height: 40))
let rectToAnimateTo = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: 40))
let layerOne = CAShapeLayer()
layerOne.path = maskPath.CGPath
layerOne.fillColor = UIColor.grayColor().CGColor
let layerTwo = CAShapeLayer()
layerTwo.mask = maskLayer
layerTwo.fillColor = UIColor.greenColor().CGColor
view.layer.addSublayer(layerOne)
view.layer.addSublayer(layerTwo)
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = rectToAnimateFrom.CGPath
animation.toValue = rectToAnimateTo.CGPath
animation.duration = 1
animation.repeatCount = 1000
animation.autoreverses = true
layerTwo.addAnimation(animation, forKey: "Nice animation")
In your code, I only see you draw the graphic once, why not draw gray part first and then draw the blue part.
I don't think it is efficient enough to implement animation in drawRect function.
You can take a look at Facebook's Shimmer Example, it simulate the effect of iPhone unlock animation. It uses a mask layer. The idea could also work in your example.
Also, Facebook's pop framework could simplify your work.

Resources