I'm drawing a UIBezierPath on a UIScrollView I have made an animation that draws the path from start to end point but this is not the animation that I want.
UIBezierPath *linePath = [UIBezierPath bezierPath];
[linePath moveToPoint:startPoints];
[linePath addLineToPoint:endPoints;
//shape layer for the line
CAShapeLayer *line = [CAShapeLayer layer];
line.path = [linePath CGPath];
// line.fillColor = [[UIColor blackColor] CGColor];
line.strokeColor = [[colors objectAtIndex:i] CGColor];
line.lineWidth = 5;
// line.contents = (id)[[UIImage imageNamed:#"Mask.png"] CGImage];
// line.contentsGravity = kCAGravityCenter;
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = 3.0;
pathAnimation.fromValue = #(0.0f);
pathAnimation.toValue = #(1.0f);
pathAnimation.repeatCount = HUGE_VAL;
[line addAnimation:pathAnimation forKey:#"strokeEnd"];
I have tried adding a contents to the shape layer but I'm bad at animations. The effect I want to achieve is the same animation as "slide to unlock" has, or a path that pulses.
I've tried to do the same thing as the answer from slide-to-unlock but can't seem to manage
I ended up dooing this:
UIBezierPath *linePath = [UIBezierPath bezierPath];
[linePath moveToPoint:startPoints];
[linePath addLineToPoint:endPoints];
//gradient layer for the line
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, 0, 150.0, 1.0);
gradient.cornerRadius = 5.0f;
gradient.startPoint = CGPointMake(0.0, 0.5);
gradient.endPoint = CGPointMake(1.0, 0.5);
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor],(id)[[UIColor whiteColor] CGColor],(id)[[UIColor blueColor] CGColor],(id)[[UIColor clearColor] CGColor], nil];
[scrollViewContent.layer addSublayer:gradient];
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
anim.path = [linePath CGPath];
anim.rotationMode = kCAAnimationRotateAuto;
anim.repeatCount = 0;
anim.duration = 1;
[gradient addAnimation:anim forKey:#"gradient"];
Related
I am using the ios default camera in my application. I would like to change something the edit view that shows after the user takes a photo.Normally, it shows a rectangle to crop, but I would like it to show a circle how would I do this.
Here is the solution which might help you to create crop overlay:-
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([navigationController.viewControllers count] == 3)
{
CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
UIView *plCropOverlay = [[[viewController.view.subviews objectAtIndex:1]subviews] objectAtIndex:0];
plCropOverlay.hidden = YES;
int position = 0;
if (screenHeight == 568)
{
position = 124;
}
else
{
position = 80;
}
CAShapeLayer *circleLayer = [CAShapeLayer layer];
UIBezierPath *path2 = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0.0f, position, 320.0f, 320.0f)];
[path2 setUsesEvenOddFillRule:YES];
[circleLayer setPath:[path2 CGPath]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 320, screenHeight-72) cornerRadius:0];
[path appendPath:path2];
[path setUsesEvenOddFillRule:YES];
CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor blackColor].CGColor;
fillLayer.opacity = 0.8;
[viewController.view.layer addSublayer:fillLayer];
UILabel *moveLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 320, 50)];
[moveLabel setText:#"Move and Scale"];
[moveLabel setTextAlignment:NSTextAlignmentCenter];
[moveLabel setTextColor:[UIColor whiteColor]];
[viewController.view addSubview:moveLabel];
}
}
I'd like to change the Speed of my "Marching ants" effect after it has looped every 10 times. So it's looping the animation with a duration of 1, after the 10 loops it should change the duration to 0.95, after 10 more seconds to 0.9 and so on....
Do you have an idea how I could do this?
Here's the code for my current animation:
CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 20);
lineLayer.position = self.view.center;
lineLayer.strokeColor = [UIColor whiteColor].CGColor;
lineLayer.lineDashPattern = #[#100];
lineLayer.lineWidth = CGRectGetHeight(lineLayer.bounds);
UIBezierPath *linePath = [UIBezierPath bezierPath];
[linePath moveToPoint:CGPointMake(0, CGRectGetMidY(lineLayer.bounds))];
[linePath addLineToPoint:CGPointMake(CGRectGetMaxX(lineLayer.bounds), CGRectGetMidY(lineLayer.bounds))];
lineLayer.path = linePath.CGPath;
// [self.view.layer addSublayer:lineLayer];
NSNumber *totalDashLenght = [lineLayer.lineDashPattern valueForKeyPath:#"#sum.self"]; // KVC is awesome :)
CABasicAnimation *animatePhase = [CABasicAnimation animationWithKeyPath:#"lineDashPhase"];
animatePhase.byValue = totalDashLenght; // using byValue means that even if the layer has a shifted phase, it will shift on top of that.
animatePhase.duration = 0.5;
animatePhase.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animatePhase.repeatCount = 10;
// [lineLayer addAnimation:animatePhase forKey:#"marching ants"];
// Create the shape layer
shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 2200.0f, 2000.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(160.0f, 1350.0f)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:20.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:200],
[NSNumber numberWithInt:100],
nil]];
// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, shapeRect);
[shapeLayer setPath:path];
CGPathRelease(path);
// Set the layer's contents
//[shapeLayer setContents:(id)[[UIImage imageNamed:#"GEIST.jpg"] CGImage]];
[[[self view] layer] addSublayer:shapeLayer];
if ([shapeLayer animationForKey:#"linePhase"])
[shapeLayer removeAnimationForKey:#"linePhase"];
else {
CABasicAnimation *dashAnimation;
dashAnimation = [CABasicAnimation
animationWithKeyPath:#"lineDashPhase"];
[dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
[dashAnimation setToValue:[NSNumber numberWithFloat:300.0f]];
[dashAnimation setDuration:1];
[dashAnimation setRepeatCount:10];
[shapeLayer addAnimation:dashAnimation forKey:#"linePhase"];
Just set yourself up to detect the end of your animation, either with a delegate method or with a completion block on the transaction. When your animation completes its ten repetitions, you can schedule a new animation with a shorter duration.
(And remember being small, playing under the table and dreaming...)
I have a UIScrollView, and I need the bottom to fade to transparent, so that it does not abruptly cut off the content. The background of the UIScrollView is a custom color. This is what I have so far, but the layer is showing up white, instead of the custom color. This is what I am going for, but only on the bottom.
:
Here is what I have so far:
maskLayer = [CAGradientLayer layer];
CGColorRef firstColor = [UIColor colorWithRed:141 green:211 blue:244 alpha:1.0].CGColor;
CGColorRef secondColor = [UIColor colorWithRed:141 green:211 blue:244 alpha:0.8].CGColor;
CGColorRef thirdColor = [UIColor colorWithRed:141 green:211 blue:244 alpha:0.2].CGColor;
CGColorRef fourthColor = [UIColor colorWithRed:141 green:211 blue:244 alpha:0.0].CGColor;
maskLayer.colors = [NSArray arrayWithObjects:(__bridge id)firstColor, (__bridge id)secondColor, (__bridge id)thirdColor, (__bridge id)fourthColor, nil];
maskLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.2],
[NSNumber numberWithFloat:0.8],
[NSNumber numberWithFloat:1.0], nil];
maskLayer.frame = CGRectMake(0, 285, self.loginScrollView.frame.size.width, 40);
maskLayer.anchorPoint = CGPointZero;
[self.loginScrollView.layer addSublayer:maskLayer];
For some reason, the layer is showing up as white, and only half the width of the scrollView.
The approach I used was to subclass UIScrollView, and create the mask layer in the layoutSubviews method.
Here's my code, which fades the top and bottom of the UIScrollView from the background colour to transparent:
#import "FadingScrollView.h"
#import <QuartzCore/QuartzCore.h>
static float const fadePercentage = 0.2;
#implementation FadingScrollView
// ...
- (void)layoutSubviews
{
[super layoutSubviews];
NSObject * transparent = (NSObject *) [[UIColor colorWithWhite:0 alpha:0] CGColor];
NSObject * opaque = (NSObject *) [[UIColor colorWithWhite:0 alpha:1] CGColor];
CALayer * maskLayer = [CALayer layer];
maskLayer.frame = self.bounds;
CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(self.bounds.origin.x, 0,
self.bounds.size.width, self.bounds.size.height);
gradientLayer.colors = [NSArray arrayWithObjects: transparent, opaque,
opaque, transparent, nil];
// Set percentage of scrollview that fades at top & bottom
gradientLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0],
[NSNumber numberWithFloat:fadePercentage],
[NSNumber numberWithFloat:1.0 - fadePercentage],
[NSNumber numberWithFloat:1], nil];
[maskLayer addSublayer:gradientLayer];
self.layer.mask = maskLayer;
}
#end
If you just want to fade the bottom, change this line:
// Fade bottom of scrollview only
gradientLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0],
[NSNumber numberWithFloat:0],
[NSNumber numberWithFloat:1.0 - fadePercentage],
[NSNumber numberWithFloat:1], nil];
When I was implementing this myself, I found this SO question helpful, and this gist on github.
EDIT: I've put this code up on github, see here.
Really like Steph Sharp's implementation, I converted it to swift and thought I'd share in case anyone else needs it.
let fadePercentage = CGFloat(0.2)
override func layoutSubviews() {
super.layoutSubviews()
var transparent = UIColor.clearColor().CGColor
var opaque = UIColor.blackColor().CGColor
var maskLayer = CALayer()
maskLayer.frame = self.bounds
var gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRectMake(self.bounds.origin.x, 0, self.bounds.size.width, self.bounds.size.height)
gradientLayer.colors = [transparent, opaque, opaque, transparent]
gradientLayer.locations = [0, fadePercentage, 1 - fadePercentage, 1]
maskLayer.addSublayer(gradientLayer)
self.layer.mask = maskLayer
}
Here goes the swift 3 version of Steph's answer:
let fadePercentage: Double = 0.2
override func layoutSubviews() {
super.layoutSubviews()
let transparent = UIColor.clear.cgColor
let opaque = UIColor.black.cgColor
let maskLayer = CALayer()
maskLayer.frame = self.bounds
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: self.bounds.origin.x, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
gradientLayer.colors = [transparent, opaque, opaque, transparent]
gradientLayer.locations = [0, NSNumber(floatLiteral: fadePercentage), NSNumber(floatLiteral: 1 - fadePercentage), 1]
maskLayer.addSublayer(gradientLayer)
self.layer.mask = maskLayer
}
Theres also this answer which does not include any subclassing.
I'm in need of an UIImage from a Masked CALayer. This is the function I use:
- (UIImage *)imageFromLayer:(CALayer *)layer
{
UIGraphicsBeginImageContext([layer frame].size);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
The problem is that the mask isn't maintained.
This is the completed code:
CAShapeLayer * layerRight= [CAShapeLayer layer];
layerRight.path = elasticoRight;
im2.layer.mask = layerRight;
CAShapeLayer * layerLeft= [CAShapeLayer layer];
layerLeft.path = elasticoLeft;
im3.layer.mask = layerLeft;
[viewImage.layer addSublayer:im2.layer];
[viewImage.layer addSublayer:im3.layer];
UIImage *image_result = [self imageFromLayer:viewImage.layer];
If I visualize the viewImage, the result is correct, but if I try to obtain the image relative to the layer, the masks are lost.
I've solved.
Now i obtaining the image mask and use CGContextClipToMask.
CGRect rect = CGRectMake(0, 0, 1024, 768);
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0);
{
[[UIColor blackColor] setFill];
UIRectFill(rect);
[[UIColor whiteColor] setFill];
UIBezierPath *leftPath = [UIBezierPath bezierPath];
// Set the starting point of the shape.
CGPoint p1 = [(NSValue *)[leftPoints objectAtIndex:0] CGPointValue];
[leftPath moveToPoint:CGPointMake(p1.x, p1.y)];
for (uint i=1; i<leftPoints.count; i++)
{
CGPoint p = [(NSValue *)[leftPoints objectAtIndex:i] CGPointValue];
[leftPath addLineToPoint:CGPointMake(p.x, p.y)];
}
[leftPath closePath];
[leftPath fill];
}
UIImage *mask = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
{
CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage);
[im_senza drawAtPoint:CGPointZero];
}
UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I am developing a maps application. I draw an animated line in the map and then use an image (a ruler image) which should be draw just over the line. To draw the line I use a CABasicAnimation with path:
-(void)lineaAnimation {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.duration = animDuration;
animation.delegate=self;
animation.repeatCount = 0;
animation.autoreverses = NO;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.fromValue = (id)inip;
animation.toValue = (id)finp;
animation.fillMode=kCAFillModeForwards;
animation.removedOnCompletion=NO;
[shapeLayer addAnimation:animation forKey:#"animatePath"];
}
-(void)linea:(CGPoint)origen to:(CGPoint)destino animado:(BOOL)anim duracion:(float)durac inicio:(float)delay {
inip = CGPathCreateMutable();
finp = CGPathCreateMutable();
CGPathMoveToPoint(inip, nil, origen.x, origen.y);
CGPathAddLineToPoint(inip, nil, origen.x, origen.y);
CGPathCloseSubpath(inip);
CGPathMoveToPoint(finp, nil, origen.x, origen.y);
CGPathAddLineToPoint(finp, nil, destino.x, destino.y);
CGPathCloseSubpath(finp);
rootLayer = [CALayer layer];
rootLayer.frame = fondo.bounds;
[fondo.layer addSublayer:rootLayer];
shapeLayer = [CAShapeLayer layer];
shapeLayer.path = inip;
UIColor *fillColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
shapeLayer.fillColor = fillColor.CGColor;
UIColor *strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
shapeLayer.strokeColor = strokeColor.CGColor;
shapeLayer.lineWidth = 5.0;
shapeLayer.fillRule = kCAFillRuleEvenOdd;
[morrallaLayer addObject:shapeLayer];
[rootLayer addSublayer:shapeLayer];
animDuration=durac;
[self performSelector:#selector(lineaAnimation) withObject:nil afterDelay:delay];
}
Then I try to move the center of the rule to the point and rotate the ruler image using this code:
delta=acos((destino.y-origen.y)/(destino.x-origen.x));
giroIni=0.0;
giroFin=delta;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
animation.fromValue= [NSNumber numberWithFloat:giroIni];
animation.toValue= [NSNumber numberWithFloat:giroFin];
animation.delegate = self;
animation.repeatCount = 0;
animation.autoreverses = NO;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.duration = animDuration;
animation.fillMode=kCAFillModeForwards;
animation.removedOnCompletion=NO;
[ruleL addAnimation:animation forKey:#"giroAngulo"];
The problem is that the ruler borderline doesn't match the line draw, there are around a degree of difference depending on the final orientation... why?
Thanks a lot!
Ooooops... sorry for your time :(
I found the problem and.. as usual the error is not in the stars but in ourselves
I use the acos function when OBVIOUSLY I should use atan