CAShapeLayer sublayer of a UIView in a UIScrollView is extremely slow - iphone

I have a custom UIView which is supposed to be a round rectangle which, when you begin editing a UILabel inside, the round rectangle will grow its shape (CABasic animation on a CAShapeLayer mask path and outline path). So to be clear, the custom UIView is organized like this:
MyCustomView has a ClipView.
ClipView uses drawRect to draw the background of the round rectangle. (clipview == view that gets clipped)
Then, I call the following code to do the CAShapeLayer manipulation:
//0. CLIP
shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = self.bounds;
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake((shapeRect.size.width)/2.0f, (shapeRect.size.height)/2.0f)];
[shapeLayer setFillColor:[[UIColor colorWithRed:0 green:1 blue:0 alpha:1.0f] CGColor]];
[shapeLayer setStrokeColor:[[UIColor redColor] CGColor] ];
[shapeLayer setLineWidth:1];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setOpacity:1];
CGRect shapeLayerPathRect = CGRectMake(0, 0, self.bounds.size.width, 44.0f);
shapeLayer.path = [self roundRectPathForRectangle:shapeLayerPathRect andRadius:CORNER_RADIUS];
[[self.clipView layer] setMask:shapeLayer];
//1. draw the shaded outline of a round rectangle
outlineLayer = [self topDownShadowShapeLayer]; //setup for my CAShapeLayer, involving shadow stuff, line color, etc
outlineLayer.path = [self roundRectPathForRectangle:shapeLayerPathRect andRadius:CORNER_RADIUS];
[self.clipView.layer addSublayer:outlineLayer];
Although the animation the proceeds is the quickest approach (stretching both CAShapeLayers), the entire element (MyCustomView) causes everything to be a lot slower! For example, UIView animations that go on, also when MyCustomView is inside a ScrollView it is VERY jumpy.
I'm mostly concerned about the UIScrollView problem. Why is it so choppy for a UIScrollView to translate these layers around? Is there a good solution / what's another approach that can achieve the same effect?

Related

How can I set maskToBounds effect on CAShapeLayer(Rounded-Recr cornered UIView)?

I want to make the glow effect spread outside of thisView.
I used this code to make Half-Rounded rect cornered UIVew.
Round two corners in UIView
Here is my code.
+ (UIView *)makeUpperHalfRoundedView:(UIView *)view {
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
UIBezierPath *roundedPath =
[UIBezierPath bezierPathWithRoundedRect:maskLayer.bounds
byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
cornerRadii:CGSizeMake(8.f, 8.f)];
maskLayer.fillColor = [[UIColor blackColor] CGColor];
maskLayer.backgroundColor = [[UIColor clearColor] CGColor];
maskLayer.path = [roundedPath CGPath];
// maskLayer.masksToBounds = NO;
//Don't add masks to layers already in the hierarchy!
UIView *superview = [view superview];
[view removeFromSuperview];
view.layer.mask = maskLayer;
[superview addSubview:view];
return view;
}
And there are two image buttons in this view closed to the boundary.
If a touch event happen on buttons, glow effect shows(showsTouchWhenHighlighted)
Before using this piece of code, I just used
thisView.layer.cornerRadius = 8;
thisVIew.layer.masksToBounds = NO;
and glow effect spread outside of 'thisView'.
But after using CAShapeLayer in 'thisView' to masking half-roused rect, the glow effect are masked by boundary.
What you're seeing is exactly how a mask is supposed to work. You are applying the mask to the layer of the superview. Let's call that view superview (just as in your code). Okay, so what will that do? It will mask superview and all its sublayers. That includes its subviews. Its subviews are actually its sublayers.
So, since the buttons are subviews of superview, they are masked like everything else inside superview.
If you don't want that to happen, don't make the buttons subviews of superview. They can sit on top of superview without being its subviews, for example.

How to get context of a CALayer plus a few pixels around it?

I am creating a layer with a shadow effect. Instead of adding it as a sublayer to my view's layer, I would like to draw it. But I am having problems being able to draw it with the shadow effect. The problem is that the context size it based on the layer size. But how do I set the rect for the context?!
CALayer *layer = [CALayer layer];
layer.frame = ...;
layer.backgroundColor = [UIColor redColor].CGColor;
layer.cornerRadius = 2.0;
layer.masksToBounds = NO;
layer.shadowColor = [[UIColor whiteColor] CGColor];
layer.shadowOffset = CGSizeMake(0, 1);
layer.shadowRadius = 0.5;
layer.shadowOpacity = 0.2;
[self.layer addSublayer:layer];
UIGraphicsBeginImageContext(layer.bounds.size);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[viewImage drawAtPoint:CGPointMake(0, 0)];
[layer removeFromSuperlayer];
With the code above, what I am getting is the box, but without a few extra pixels of padding with the shadow (on all four sides). If I increase the size of the ImageContext, all I get is more height and width, but still starting from x=0 and y=0, where I would want it to start from x=-5, y=-5 or something like that.
Thanks a bunch!
Make your context 10 pixels larger in both the x and the y.
Then before you draw your layer do a CGContextTranslateCTM(context,5,5);
Hope this helps!
I'm not sure if the following is your problem, but it just caught my eye.
[self.layer addSublayer:layer];
UIGraphicsBeginImageContext(layer.bounds.size);
[layer renderInContext:UIGraphicsGetCurrentContext()];
It looks like you have a property on this file called layer, which you are adding the shadow layer you've created to. You then get the context based on the current CALayer, as opposed to self.layer.
I typically use CALayer to modify UIImageView, and do not have a need to add sub layers, so perhaps that code is fine. Just wanted to point it out, please do let me know if which way is accurate, as I always like to learn.
~Good Luck

use a CALayer as a UIImageView

I would like to create a CALayer bezier path in a circle shape. And I would like to set it like it was a UIImageView (to be able to move it with animation etc.) Is it possible? If so how can I do it? Thank you.
You could always add a CAShapeLayer to your view. During init, do something like (all untested):
CAShapeLayer *circle = [[CAShapeLayer alloc] init];
[self.layer addSublayer:circle];
Then, in drawRect, layoutSubViews, or some other place that seems appropriate to update the layout:
circle.fillColor = [[UIColor redColor].CGColor;
CGMutablePathRef p = CGPathCreateMutable();
CGPathAddEllipseInRect(p, NULL, self.bounds);
circle.path = p;
circle.bounds = self.bounds;
circle.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
I'm not sure what you mean by a "CALayer bezier path" but you have a couple of options here:
Create a subclass of UIView, where you draw your circle using UIBezierPath methods in the drawRect:. This view can then be added to another view as a subview and animated using standard methods. However, you are warned that this may affect performance, (as it has to keep re-drawing) so if that does turn out to be a problem...
Create a graphics context and draw your circle in there. Take an image from this graphics context and set it as the image for a UIImageView. Animate as in answer (1). This way you aren't redrawing all the time so performance would be better, but try with option 1 first as it is simpler, and if you have simple drawing code it shouldn't affect you too much.
For option 2, you begin a graphics context using UIGraphicsBeginImageContextWithOptions - you then do your drawing, and extract the image using UIGraphicsGetImageFromCurrentImageContext, then end the context using UIGraphicsEndImageContext. Those functions are all documented here
Sample code to do this:
CGFloat radius = 50;
CGSize size = CGSizeMake(radius*2,radius*2);
CGPoint centre = CGPointMake(radius,radius);
UIGraphicsBeginImageContextWithOptions(size,NO, 0.0);
UIBezierPath * solidPath = [UIBezierPath bezierPathWithArcCenter:centre radius:edgeSize/20 startAngle:0 endAngle:2 * M_PI clockwise:YES];
[solidPath closePath];
[[UIColor whiteColor] set];
[solidPath fill];
UIImage *circle = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithImage:circle];

Shadow not appearing for UIView using CALayer

I have a subclassed UIView loaded from a nib, and I cannot get a shadow to draw around it. I'm trying to get a shadow to appear around the entire view for quite some time now. I elected to place it in it's own sublayer to simplify animating it later. Here's the code:
-(void)awakeFromNib
{
self.clipsToBounds = NO;
// set up the shadow layer
CALayer *shadow = [CALayer layer];
shadow.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height);
shadow.shadowColor = [UIColor blueColor].CGColor;
shadow.shadowRadius = 15.0;
shadow.opacity = 1.0;
[self.layer addSublayer:shadow];
// I set this property so I have access to it later to more easily animate it.
self.shadowLayer = shadow;
}
When I NSLog the shadowLayer property, the coordinates and frame are correct. It's matches the view it's backing.
I also set a border color and corner radius on self.layer and it appears correctly. If I put the shadow on self.layer it appears but it encompasses all the subviews of my parent UIView.
Any help is greatly appreciated.
Am assuming you have QuartzCore imported. I think you need to set & create a border to the UIView. The way to use this [self roundedLayerWithShadow:yourView.layer radius:5.0f];
- (void)roundedLayerWithShadow:(CALayer *)viewLayer
radius:(float)r
{
[viewLayer setMasksToBounds:YES];
[viewLayer setCornerRadius:r];
[viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
[viewLayer setBorderWidth:1.0f];
[viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
[viewLayer setShadowOffset:CGSizeMake(0, 0)];
[viewLayer setShadowOpacity:1];
[viewLayer setShadowRadius:2.0];
return;
}
I struggled with the same, and it turns out you need to set shadowOpacity to 1.0. In your code you accidentally use opacity instead of shadowOpacity. That's the same issue I had.
In general, for the shadow to appear:
the shadowOpacity should be larger than 0
the shadowRadius should be larger than 0
the masksToBounds should be set to false (to avoid the clipping of the shadow)
the shadowColor should be different than the background color of the view's superview
Swift 4.2. example implementation:
let myCustomView = MyCustomView()
myCustomView.layer.shadowColor = UIColor.black.cgColor
myCustomView.layer.shadowOpacity = 0.15
myCustomView.layer.shadowRadius = 5
myCustomView.layer.masksToBounds = false
myCustomView.layer.shadowOffset = CGSize(width: 0, height: 2)
Aside from borderRadius, your shadow layer looks very much transparent. Therefore it will not drop any shadow on shadow.superlayer.

"Masking" an animation? iPhone SDK

I have been looking into ways of masking images on the iPhone. I came across this solution
http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html
which works great for still images. What I want to do is mask an animation in a UIImageView. From what I have read I don't think this is possible whilst also achieving a decent frame rate.
This leads me to ask whether the following is possible, could I "clip" the images inside the UIImageView? ie not re-size the UIImageView to the size of the images so some parts are chopped off?
I haven't tried this for performance, but you can use a Core Animation layer as a mask. You can define a path to use in a CAShapeLayer and fill the shape. Then specify the layer mask of your UIImageView's layer. Something like:
CGMutablePathRef path = CGPathCreateMutable();
// build the path by adding points
// ...
CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
[shapeLayer setPath:path];
[shapeLayer setFillColor:[[UIColor blackColor] CGColor]];
// Set shape layer bounds and position
// ...
// Set the mask for the image view's layer
[[imageView layer] setMask:shapeLayer];
Keep in mind that this isn't actually creating a new image as the link you reference does. This just creates a mask for display over top of your image view--which may not be what you want.
I searched high and low and finally found a solution with practically no limitations at all. So, here you go:
UIImageView *maskeeImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"MaskeeImage.png"]];
[maskeeImage setAnimationRepeatCount:-1];
[maskeeImage setAnimationImages:[[NSArray alloc] initWithObjects:[UIImage imageNamed:#"MaskeeImage1.png"], [UIImage imageNamed:#"MaskeeImage2.png"], [UIImage imageNamed:#"MaskeeImage3.png"], nil]];
[maskeeImage startAnimating];
CALayer *maskeeLayer = [maskeeImage layer];
maskeeLayer = CGRectMake(0, 0, 768, 1004);
[[[self view] layer] addSublayer:maskeeLayer];
UIImage *maskImage = [UIImage imageNamed:#"ImageMask.png"];
CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (id) myImageMask.CGImage;
maskLayer.frame = CGRectMake(0, 0, 768, 1004);
[maskeeLayer setMask:maskLayer];
There you go! It's actually really easy, once you know how. I tried to show a few different options; Using UIImageViews or UIImages, Animations (Which can also be used for the mask).
To sum it all up, you basically have to set the mask property on your view's CALayer. Every UIView subclass has a CALayer attached to it, so you aren't restricted at all in terms of where you get your mask or maskee from.
Hope this helped. Cheers, Dylan.